Compare commits

...

292 Commits

Author SHA1 Message Date
Changwei Ye
7bf873996c osd: Re-arm scrub timer for remaining scheduled PGs in pick_next_scrub
When pick_next_scrub finishes due PGs and skips PGs whose next_scrub is still
in the future, track the earliest remaining PG and call schedule_scrub on it
before returning 0.

Otherwise, after the single OSD scrub timer fires, any remaining PG with a
later next_scrub (even within the same pool, e.g. due to staggered scrub
completion times, PG migration, different pool intervals, or manual schedules)
is left without a timer until the finished PG's next cycle (auto_scrub=true)
or indefinitely (auto_scrub=false).

Add regression tests covering both auto_scrub=false and auto_scrub=true.
2026-12-04 13:55:54 +08:00
37a643fd02 Allow vm-vol and vm-state in _monkey_patch_qemu_blockdev_options 2026-12-04 00:28:11 +03:00
265f00cd3f kv: Set finished before the stdin handler removes itself (#216)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#216
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-04 00:19:51 +03:00
def62d401d mon: Do not truncate per-OSD iops before summing them (#224)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#224
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-04 00:18:52 +03:00
f3fd41d12c Fix rm-data waiting forever when PGs go inactive during deletion (#203)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#203
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-03 19:31:54 +03:00
027ef85d5d mon: Keep positions of surviving OSDs in EC PGs on re-layout (#214)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#214
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-02 19:51:57 +03:00
ec74399871 osd: Move the PG epoch only when reporting it for the first modification (#219)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#219
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-02 13:11:29 +03:00
f7793e37c1 Store v1: Roll back over a stable deletion instead of returning EBUSY (#220)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#220
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-02 10:47:37 +03:00
fae749d515 osd: Put the current OSD set into the PG history when a peering flush reports the epoch (#217)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#217
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-12-02 01:36:18 +03:00
913f70c2dd Force zero byte before qobject_from_json 2026-11-30 01:06:21 +03:00
e2544bf34f QEMU driver - return 0 instead of byte count on success 2026-11-30 01:03:35 +03:00
97baef8cdf Client: Keep the listing timer armed while PGs wait to become active (#201)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#201
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 14:15:55 +03:00
00bd701a97 mon: Add sticky_primaries to keep live primaries and balance new ones (#198)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#198
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 14:14:50 +03:00
9d695fe690 http_client: don't arm the websocket timeout after a failed connect (#204)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#204
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 14:13:57 +03:00
08e00c9300 osd: Send queued replies before a peering calculation (#199)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#199
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 14:13:13 +03:00
2cc6942c7a osd: Merge object lists on peering instead of copying and sorting them (#180)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#180
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 14:12:35 +03:00
c3a4398792 osd: Yield between peering calcs started from continue_pg() too (#200)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#200
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-29 13:52:22 +03:00
54b8d2c0ed osd: Let the event loop run between PG peering calculations (#197)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#197
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-28 11:19:19 +03:00
dade4372b1 Show NBD devices above a numbering gap in vitastor-nbd ls
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#193
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-27 19:02:04 +03:00
6b103473c5 Add --with-snapshots to vitastor-cli modify --rename (#191)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#191
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-27 18:46:46 +03:00
d3b893ae2b Fix test_http_client leak 2026-11-27 17:30:14 +03:00
4810971d96 Open the device read-only in vitastor-nbd unmap (#162)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#162
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-27 13:55:07 +03:00
1b4f036b4e http_client: don't arm the timeout of a request that has already failed (#184)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#184
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-27 13:38:28 +03:00
1544fcdb3a Fix seed 179088455 (tombstone cleanup wakeup) 2026-11-27 01:03:16 +03:00
5d9d404c8b test_pg_chaos: Treat ops lost in a crash or takeover as OPTIONAL (#159)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#159
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-26 16:07:54 +03:00
6601ad9265 client: Fix CAS writes and buffer cleanup with write-back and immediate_commit (#196)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#196
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-26 16:05:52 +03:00
884727af62 Fix zero-length memcpy from NULL found by UBSan (#173)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#173
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-25 20:53:11 +03:00
49e76ea850 OSD: Reject inverted ranges in primary LIST (#176)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#176
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-25 20:52:18 +03:00
7cb1edb522 client: Check CAS writes for multiple stripes after slicing them (#175)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#175
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-25 20:33:55 +03:00
5133d5caba Ignore image resize events after disconnect in vitastor-nbd and vitastor-ublk (#156)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#156
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-25 14:42:34 +03:00
de3644bc00 Use the epoll-based client in qemu_driver when io_uring isn't available (#151)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#151
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 12:44:08 +03:00
6dc8758ed8 osd: Fix scrub object state pins: crash when the object becomes clean, leak in scrub_recalc_state (#158)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#158
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 12:36:38 +03:00
b21b09effb osd: Fix an endless retry of a chained read when the object state goes away (#167)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#167
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 12:35:17 +03:00
5532770ea4 osd: Free the old object state in mark_object() only after inserting the new one (#169)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#169
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 12:25:40 +03:00
2df2a50b2f osd: Don't mark a copy of a chained read's layer object lost on ENOENT from a racing delete (#168)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#168
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:53:39 +03:00
f2de842662 osd: Use role 0 for tombstone copies in replicated pools, revert the stripes guard (#161)
Revert 3e4aa533 + fix actual root cause

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#161
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:52:21 +03:00
58ddb3b068 osd: Finish a read with -EPIPE when its PG stops instead of marking copies corrupted (#164)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#164
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:50:46 +03:00
c2117bc930 Store v1: Fix writes over a deletion hanging with immediate_commit=all (#165)
Follow-up to #149, which broke this.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#165
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:49:03 +03:00
14c1341213 Return the read error instead of EDOM when a disk read fails (#166)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#166
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:46:48 +03:00
eb51a5d978 osd: Fail a chained read on an incomplete replicated object instead of aborting (#170)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#170
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-24 03:43:29 +03:00
4ee30fa775 Store v1: Fix two flusher bugs with deletions (#114)
Two store v1 flusher bugs. Both happen with immediate_commit=all too.

1. Store v1: Wake up the flusher when journal sectors are written (`test_blockstore_chaos --seed 5 --config 12 --steps 30000 --p-delete 30`)
2. Store v1: Do not queue a deletion for flushing again while it is being flushed (`test_blockstore_chaos --seed 60 --config 21 --p-delete 30`)

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#114
Co-authored-by: koolkhel <koolkhel@mail.ru>
Co-committed-by: koolkhel <koolkhel@mail.ru>
2026-11-23 00:13:10 +03:00
74fea63bfa vitastor-disk: Exit with 1 if prepare fails to initialize an OSD and return skipped disks (#137)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#137
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-23 00:10:40 +03:00
9ebdc0ef89 Report invalid osd_network as a fatal error instead of an exception (#152)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#152
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-23 00:09:18 +03:00
e9570efe99 Store v1: Don't let the ack of an older big write unblock later small writes (#149)
The same problem as #129, in the immediate_commit=all path.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#149
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-22 23:06:50 +03:00
c3d082368a Unregister the NBD socket from epoll before closing it in vitastor-nbd
vitastor-nbd closed the NBD socket on NBD_CMD_DISC and on hang-up
without removing its epoll handler. The next socket that got the same
descriptor number then lost its handler: set_fd_handler() tried
EPOLL_CTL_MOD for it, got ENOENT and dropped the entry.

After the close the process only has the final sync left, so this hits
the first connection opened during it.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-11-22 23:02:09 +03:00
f0afdce8b0 osd: Use one timestamp for picking recovery and arming its retry timer (#146)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#146
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-22 22:57:26 +03:00
36e38503e7 Always set SUPPORT_LEFT_ON_DEAD 2026-11-22 18:39:47 +03:00
87dceccf38 Remove the outdated KNOWN ISSUE from arch doc 2026-11-22 18:30:05 +03:00
c365fd74ab Simplify register_tombstone (remove known_locs) 2026-11-22 18:28:52 +03:00
02d029dc33 Simplify subop freeing (also fixes cleanup on SYNC with failed deletions) 2026-11-22 18:28:52 +03:00
d5af419a91 Cleanup tombstones inline during deletion when possible (immediate_commit + no left_on_dead) 2026-11-22 18:28:52 +03:00
a211741edb Fix PG object counters for tombstone deletions (tombstones are included in total_count) 2026-11-22 18:28:52 +03:00
483f581813 Never fall back to /dev/nbd0 in vitastor-nbd unmap and revive (#120)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Vitaliy Idelson <v.idelson@mindsw.io>
Reviewed-on: vitalif/vitastor#120
Co-authored-by: koolkhel <koolkhel@mail.ru>
Co-committed-by: koolkhel <koolkhel@mail.ru>
2026-11-22 15:12:02 +03:00
ce33722edf vitastor-disk: Accept symlinks to whole disks in prepare (#134)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#134
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-22 15:09:52 +03:00
3bf0b45a18 Pin object state while reading 2026-11-22 14:03:54 +03:00
019d644a88 Implement tombstone-based deletion for the new store 2026-11-22 14:03:54 +03:00
89201f39e0 Fix fsync not waiting for previous in-progress fsync 2026-11-22 01:09:40 +03:00
3e4aa53357 Fix buffer overflow on mark_object_corrupted in a replica pool 2026-11-22 01:09:40 +03:00
8dc2f0b07a Include libnl3 in buildenv 2026-11-21 18:05:06 +03:00
5ec30ca166 osd: Pause recovery of a PG after an error instead of retrying it in a loop (#143)
Now a failed recovery operation (except EPIPE) pauses recovery of its PG for 1 second, doubling up to 60 seconds while it keeps failing, and a successful one resets the pause.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#143
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-21 12:53:45 +03:00
7cc4553e01 Fix vitastor-nbd spinning forever after NBD_CMD_DISC (#142)
The NBD_CMD_DISC branch closed the socket and returned without
preparing the next read, so handle_read() looped forever on any bytes
that followed the disconnect request in the same recvmsg(), ignoring
`stop` and SIGTERM. The kernel sends such requests after the
NBD_DISCONNECT ioctl, for example when the device is opened and its
partition table is re-read.

The closed descriptor also stayed in use: a read or a reply submitted
after it failed with EBADF, and the process exited with code 1 in the
middle of the final sync. Forget the descriptor once it is closed and
stop parsing, reading and sending after that.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-21 11:28:19 +03:00
e4030c9f73 Store v2: Do not return unstable entries beyond the listing page (#136)
BS_OP_LIST with list_stable_limit promises unstable versions only from
the range of the returned stable objects, and the old store keeps to it.
The new store returned every unstable version of the PG, so a paged
caller (scrub, locally or through SEC_LIST) got the ones past the page
and got them again with the next page. Drop them once the page is full,
also when it is filled exactly to the limit.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: koolkhel <koolkhel@mail.ru>
Co-committed-by: koolkhel <koolkhel@mail.ru>
2026-11-21 11:26:02 +03:00
cf5c466e83 cli/dd: Keep in-order output going after ignored errors (#133)
With conv=noerror a failed read dropped its block and a failed write
dropped its buffer. An output written in order (a pipe, oflag=append)
then waited for that block forever, spinning the copy loop.

A failed read from an image or a seekable input now gives a block of
zeros, which is what a seekable output already got as a hole. A stream
has no block to skip, so its read error ends the copy with an error,
also with conv=noerror. In-order writes advance by the blocks taken,
not by the bytes written, so an ignored write error does not stop them.
A write takes its block only once it has an io_uring sqe, so a full
ring no longer drops the block.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#133
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-20 19:33:14 +03:00
63f51d602f vitastor-disk: Refuse a disk given both as data and in --fast-devices (#135)
prepare collects the device list and --fast-devices separately, so a
disk given in both got two entries, each with its own copy of the
partition table, and they overwrote each other's new partitions. The
data partition of such a disk was dropped right after it was created,
its OSD was not initialized, and the journal and metadata partitions
made for it were left behind.

Refuse such a command before anything is changed.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#135
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-20 19:20:11 +03:00
971d45def6 osd: Stop on SIGINT/SIGTERM from the main loop, not the signal handler (#141)
The handler called osd_t::force_stop(), which builds a JSON object,
allocates strings and starts an HTTP request to etcd. None of that is
async-signal-safe. When the signal interrupts malloc() or free() in the
main loop, the handler re-enters the allocator and corrupts the heap,
and the OSD dies in malloc with SIGSEGV or SIGABRT instead of exiting
with 0.

Only set a flag in the handler, like the NBD, UBLK and NFS servers do,
and call force_stop() from the main loop. A second signal still exits
at once, now with _exit().

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Reviewed-on: vitalif/vitastor#141
Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-20 19:10:54 +03:00
2fc65145fb Report netlink-map failures in its exit status (#121)
netlink-map and netlink-revive forked before configuring the device, and
the parent exited 0 at once. So a failed configuration (a busy device,
no permission, no nbd netlink family) still returned 0, and the command
could return before the device was set up.

Fork once before setting up the device in both map modes, the way
vitastor-ublk does: the parent waits for the daemon to send the device
number, prints it and exits 0, or exits 1 if the daemon dies first. The
ioctl setup child no longer forks on its own, and failed tries are
reaped. map now prints the device also when it is given explicitly.

- [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-20 19:04:13 +03:00
c9617bc9e0 vitastor-disk: pass config_path to vitastor-cli/vitastor-osd 2026-11-20 18:52:34 +03:00
db0622c576 Store v1: Fix false checksum mismatches of reads running in parallel to a flush
A read of a clean block which was still running when the same data was
overwritten and flushed could fail with a false -EDOM in two cases:

- The flush moved the object to a new block (redirect-write). The metadata
  entry of the old block is zeroed out, in memory too, so the read verified
  its data against zero bitmap and checksums. Only the new location was
  marked as changed in used_clean_objects.
- csum_block_size == bitmap_granularity and the same blocks were overwritten
  in place. The read verified old data against new checksums, because this
  branch never skipped verification.

Mark the old location as changed too, and do not verify clean data in the
second branch if its location was changed during the read. Reads which start
during a flush are still verified there, because they take the overwritten
blocks from the journal.
2026-11-20 18:21:19 +03:00
64b2265aa4 Store v1: Do not skip checksum verification of reads that start after a parallel flush
used_clean_obj_t::was_changed was set by a flush (or by a read started
during one) and never reset while the entry had references, so a read
started after the flush had finished, but while an older read still held
the same clean block, also returned data without verifying checksums.
Count flushes in the entry instead and remember the count at the start
of each read, skipping verification only if it changed or a flush was
already running.
2026-11-20 18:21:19 +03:00
7c76601c45 osd: Test peering flush batches waiting for the PG history (#132)
Add two more tests for #131

- `test_peering_flush_waiting_batch_repeer`: EC 2+1, a peering flush batch waits for the history with the holders to be reported, and OSD 3 drops out before the report lands. The batch is dropped without sending any stable or rollback op, and the PG peers again. Without the `continue_pg()` in the drop branch of `on_change_pg_history_hook()` the PG stays repeering and the test fails.
- `test_peering_flush_replicated_history`: replicated pool, v2 stable on OSD 1 and unstable on OSD 2. OSDs 1 and 2 are in the history before the flush is sent. It fails if replicated pools are skipped when adding the holders.

- [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-19 15:30:15 +03:00
4ad3c8037d Store v1: Don't let a sync of an older big write unblock later small writes (#129)
A small write following an unsynced big write waits in `WAIT_BIG` until that big write is synced, because a big write only gets its journal entry from the sync. `ack_sync()` unblocked every `WAIT_BIG` write of the object after any synced big write, including the ones waiting for a newer big write which that sync didn't cover. Their journal entries could then reach the disk before the newer big write's entry, and after a crash or restart the replay put them on top of the older big write, giving a version that was never written.

vitalif/vitastor#129

- [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-19 15:25:28 +03:00
ac3f6f85fc osd: Keep the holders of unstable EC versions in the PG history and accept them from pg_data_size roles (#131)
368daa4b made a new has_incomplete case possible: object write to 1,2,3 -> stabilize on 1 -> crash -> repeer on 2,3 -> rollback -> repeer on 1,2,3 -> has_incomplete.

So the threshold for an unstable EC version must pg_data_size, but to fix the original problem we also need to add stabilized target sets into the PG history.

Details in vitalif/vitastor#131

- [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-11-19 13:58:37 +03:00
8582f82356 vitastor-disk: Write csum_block_size 0 in JE_START without data checksums
With a manual layout, write-journal takes data_csum_type and
csum_block_size from the JSON "start" entry and otherwise keeps the
blockstore_disk_t defaults. calc_lengths(), which zeroes csum_block_size
when there are no checksums, is not run for a manual layout. So a JSON
without a "start" entry produced JE_START with data_csum_type none and
csum_block_size 4096, and raw-resize then refused the journal: "journal
header has different checksum parameters: none/4096 vs none/0".

Zero csum_block_size when there are no data checksums.
2026-11-17 23:40:18 +03:00
e2d7674cd5 allocator: Fix find_free() returning a block past the end when full
An allocator of 2-63 blocks has a single-level mask with no parent bit
to mark it full, and the mask bits past the end are always zero. So
find_free() on a full allocator returned the first index past the end
instead of UINT64_MAX. Store v1 then submitted a big write past the end
of its data area (the bounds assert in dequeue_write() fires) instead
of failing it with ENOSPC. Store v2 and vitastor-disk raw-resize use
the same call.

Check the leaf index against the allocator size, and cover sizes 2, 63
and 64 in test_allocator.
2026-11-17 23:37:00 +03:00
48d53ef69f vitastor-disk: Fix stable/rollback handling in index_journal_by_object
The "stable" and "rollback" branches read the "version" key, but
dump-journal writes the version as "ver". So both target versions were
always 0: "stable" marked every write of the object stable, and
"rollback" removed nothing. The rollback loop also counted down with a
size_t and "i >= 0", so it never ended and read before the vector.

Read "ver", and count down with an int as elsewhere in the code.

The function is only used to convert older metadata with its journal in
write_json_heap(), and write_json_meta() only calls write_json_heap()
for "3.0" metadata, so that path isn't reachable yet. There is no test
harness for vitastor-disk internals, so this comes without a test.
2026-11-17 21:13:02 +03:00
1ba35c3b5e Free NBD netlink sockets with nl_socket_free()
netlink_sock_free() released the socket from nl_socket_alloc() with a
plain free(), leaking its file descriptor and its callback set. With
LeakSanitizer, netlink-unmap then exits with a non-zero code.
2026-11-17 10:21:45 +03:00
e1f945f443 osd: Recalculate object state online when scrub finds its target version deleted
Peering left older pieces on their target OSDs out of the object state,
so an incomplete EC object with its newest version on one OSD only was
tracked with that piece alone. When vitastor-cli fix --check no removed
it, scrub found nothing and forgot the object: reads returned zeros in
place of the removed piece, and a write made them permanent, although
the previous version was still readable from the other OSDs.

List every OSD holding any version of the object in its state, once per
role. When scrub finds no piece of the target version but outdated
pieces are left, ask their OSDs for versions with SEC_READ_BMP and
recalculate the object state online: the newest version becomes the
target, older ones stay outdated, and pieces which are gone are dropped.
The object is forgotten only if nothing is left, and without the
unbalanced deref_object_state() it did before.
2026-11-16 20:25:57 +03:00
7a95269a05 osd: Keep pg_config history in sync when a write adds the current OSD set
The first write to a PG which isn't clean adds the current OSD set to
pg.target_history before the new history is reported to etcd. An etcd
event handled in between made apply_pg_config() compare it with the old
history in pg_config and stop the PG, so the PG was re-peered for
nothing. It happened on the first recovery write right after a PG state
report. Update the pg_config history at the same time, like peering
does when it clears the history of an active PG.
2026-11-16 20:25:57 +03:00
eea278cfc5 Fix test_msgr_stop 2026-11-16 19:29:56 +03:00
beb52fdf16 Client: Retry a failed config reload instead of failing the running client
A client reloads the global config when etcd cancels its watch on a
compacted revision. With client_infinite_start off, which is the default,
one etcd error during that reload goes to fatal_error() and exits the
process (or aborts the client when exit_on_error is off), although the
client is already serving I/O with a valid configuration. Retry the
reload by timer instead, as with infinite_start.
2026-11-16 16:36:29 +03:00
ef76796a1d Fix keepalive during major recalc PG 2026-11-12 15:09:33 +03:00
ccfacd1c6b Fix possible clients.at failure on write throttling & client disconnect 2026-11-10 15:26:19 +03:00
3f9cd01867 exit() on fatal errors after initialization in qemu_driver again to not leave hung VMs 2026-11-04 01:13:50 +03:00
a7a6d5f38e Add tests to readme-ru 2026-11-01 22:03:16 +03:00
01b501c686 Release 3.2.3
Bugfix release, also including a new PG chaos test

- Data correctness
  - Fixed fsync replay logic in the client library
  - Fixed possible incorrect marking of replicated objects as HAS_INCOMPLETE during a
    partially successful write while moving the object to another OSD set
  - Fixed PG hanging when the queue simultaneously contained an active
    write operation and an initial flush of the same object
  - Fixed a case of incorrect computation of EC object states during PG peering
  - Fixed possible read errors during concurrent writes or deletions
  - Fixed possible failure to report PG state when the OSD didn't acquire the lease yet
  - Fixed theoretically incorrect marking of replicated objects as DEGRADED on state change
  - Fixed read errors from images with more than 255 snapshots
  - Parallel removal of multiple snapshots of the same image from two processes now fails
    with an error instead of corrupting the snapshot chain
- New and old stores
  - New store: fixed big writes hanging after a single redirect_intent write
  - New store: fixed several potential data loss errors in rare cases found by chaos tests:
    incorrect checksum handling for empty writes, incorrect object write after its rollback
    to version zero, reuse after restart of sequence numbers below the completed_lsn in the header
  - Old store: fixed a rare OSD hang when deleting an object
- Network & security
  - Fixed transport encryption breaking with OpenSSL versions containing the unfixed bug #27302
  - Added options for QoS in RDMA networks with PFC: rdma_traffic_class, rdma_sl, rdma_set_flow_label
  - Vault: the client now retries loading keys on error automatically
  - Vault: fixed read errors from clones of encrypted images
  - Check read access to the parent image when creating a clone
  - Retry DNS resolve errors instead of killing the client process
- VitastorFS
  - Deleting a directory with many previously deleted files is now faster because fewer
    redundant keys are scanned in the key-value database
  - Fixed an error when moving a directory over another empty directory
- vitastor-cli
  - `fix` and `describe` no longer hang when one of the OSDs is unavailable: such OSDs are
    skipped with a warning, and the exit code indicates an incomplete result
  - `describe --inode` shows all objects of an image, not just one
  - `osd-tree` crashed on etcd errors
  - `ls --tree` hid images with a filtered-out parent
  - `ls-pgs` printed an empty table instead of the real error and showed misplaced data as degraded
  - `dd`: copying a pipe without `count=` copied only 1 MB, `oflag=append` didn't work,
    `status=none` and `status=noxfer` were ignored, devices like /dev/mem couldn't be read
  - `create-pool`/`modify-pool` now refuse pg_size > 64 and renaming a pool to an occupied
    name; `level_placement` rules can be reset with an empty value
  - `modify --resize` silently accepted a broken size like "1.5G"
  - `rm-data` didn't validate offset boundaries
  - Fixed minor differences between help, docs and the actual behaviour
- Deployment
  - Partitions with the Vitastor partition type are now owned by the vitastor user even when
    they don't yet contain a valid superblock
  - Fixed the QEMU driver build on QEMU versions patched by RHEL 9.1
  - Fixed a small memory leak when destroying the QEMU driver
  - The client now has a mode that handles fatal errors instead of silently killing the whole
    client process via exit(1). New QEMU driver versions use this mode and should no longer
    take the QEMU process down when a disk fails to connect
2026-11-01 20:10:42 +03:00
59e91f595d Fix parallel removal of snapshots (actually make it fail) by adding more CAS checks 2026-11-01 17:28:59 +03:00
d75df73c3a Add blockstore chaos test docs 2026-11-01 14:19:38 +03:00
f539bba0eb Add missing free()s to qemu_driver 2026-10-31 17:12:10 +03:00
ddcd3aef87 Allow to capture errors in client instead of just calling exit(1) 2026-10-31 14:36:58 +03:00
977b084af8 Change cluster_client_t::msgr to unique_ptr 2026-10-31 14:29:33 +03:00
e0b683a634 Fix config/this->config ambiguity in client constructor 2026-10-31 14:27:33 +03:00
ac808fefe7 Retry resolve errors instead of exiting 2026-10-31 12:15:11 +03:00
c4defad6bf Clear all timers on etcd_state_client_http destruction 2026-10-31 12:15:11 +03:00
bbcfe3e258 Set ownership of OSD partitions in a udev rule of its own (#109)
udev skips every key of a rule whose `IMPORT{program}` fails, `OWNER` and `GROUP` included, and `vitastor-disk udev` exits 1 when it rejects the superblock. A freshly added partition whose check failed stayed `root:disk`, and an OSD opening it as user vitastor got EACCES. This happens with dm-multipath: the dm partition's ready event is checked while `/dev/disk/by-partuuid` still points at the path partition. Assign ownership by partition type alone (in `mon/scripts/` and `docker/`); the alias symlink and the OSD start still need a valid superblock.

Tested: `udevadm test` on systemd 249 and 252 with a failing IMPORT — before: no OWNER/GROUP/SYMLINK; after: OWNER/GROUP applied, SYMLINK not. On a VM, a partition re-added by PCI remove/rescan while another device carried its PARTUUID came back `root:disk` before and owned by the OSD user after.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-10-28 00:17:45 +03:00
c0d6a417ba NFS: Fix UBSan memcpy from NULL error (#112)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: koolkhel <koolkhel@mail.ru>
Co-committed-by: koolkhel <koolkhel@mail.ru>
2026-10-28 00:10:43 +03:00
23b9bff8fb Add a rename-dir test to test_nfs 2026-10-28 00:09:31 +03:00
Yury Luneff
e2c5ec8824 Stop NFS prefix scans at the end of the prefix
The emptiness checks of RMDIR and of RENAME over a directory, READDIR
and the defrag scans list a key prefix. They now stop at the end of the
prefix instead of running on to the next existing key through blocks
emptied by deletes, which made RMDIR slower with every deleted file.

This also fixes RENAME of a directory over an empty directory failing
with ENOTEMPTY: its check took the first key after the prefix, which
belongs to another directory or inode, for an entry.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-28 00:01:52 +03:00
Yury Luneff
0757a1e8b9 Add an end key to K/V listings
A listing goes on from block to block until it finds a key, and blocks
emptied by deletes are never freed. So a listing that runs past the end
of its range reads every empty block up to the next existing key, each
with a version check on an OSD. After many creates and deletes, this
made a single RMDIR in the NFS proxy take hundreds of milliseconds.

list_start(start, end) stops at the first key >= end and does not read
blocks beyond it. vitastor-kv list/dump/dumpjson now pass their end
argument.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-28 00:00:15 +03:00
cfaa3feefa Exit with code 1 instead of aborting when the OSD fails to open its devices
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-27 23:56:01 +03:00
4e638b2681 Fix UBSan signed shift overflow in sha256_transform() (#113)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: koolkhel <koolkhel@mail.ru>
Co-committed-by: koolkhel <koolkhel@mail.ru>
2026-10-27 23:53:58 +03:00
3e803e07d6 Fix that UAF from Yury Luneff :) 2026-10-26 01:46:06 +03:00
Yury Luneff
d5465622ed Add a test for UAF in continue_ops() on slice_rw() failure
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-26 01:45:35 +03:00
63dc07b4c9 Validate min_offset / max_offset in rm-data 2026-10-25 22:37:06 +03:00
a39319beb7 Fix vitastor-cli ls --tree hiding layers whose parent is filtered out (#101)
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:24:53 +03:00
801231e8d4 Fix vitastor-cli ls-pgs printing an empty table instead of an error
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:23:10 +03:00
33195f9c41 Fix vitastor-cli ls-pgs DEGRADED column showing misplaced data
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:22:37 +03:00
aca9dcb1a9 Tests to yaml 2026-10-25 22:19:29 +03:00
9d1489c86f Remove json_printed flag 2026-10-25 22:19:29 +03:00
be897e278c Fix vitastor-cli fix hanging when an OSD is down
The client queues a request to an OSD which is down until the OSD comes
back, so fix hung forever when the primary of an object's PG or one of
--bad-osds was down. Refuse to start while one of --bad-osds is down,
skip objects whose PG primary is down as it is done for inactive PGs,
and exit with EIO when some objects were skipped or a request failed,
so that a partial repair is not taken for a complete one.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:19:27 +03:00
b06faf04cb Fix vitastor-cli describe hanging when an OSD is down
The client queues a request to an OSD which is down until the OSD comes
back, so describe hung forever when a PG primary or an OSD from --osds
was down. Skip such PGs and OSDs with a warning, ask only the primary
of the PG when --pool and --pg are given, and exit with EIO after
printing what could be listed, so that a partial listing is not taken
for a complete one. With --json, stdout stays a valid JSON array.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:19:25 +03:00
54b3376d00 Fix vitastor-cli describe listing only one object with --inode
describe --inode sent the range from offset 0 to offset 0 of the inode
and ignored --min-offset and --max-offset, and --max-inode without
--max-offset also ended the range at offset 0 of that inode. The OSD
ends the listing at (max_inode, max_offset) inclusive, so only the
object at offset 0 of the last inode was listed. Honour the offsets
with --inode and end the range at the last offset of max_inode when
--max-offset is not given.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 22:19:23 +03:00
7622bbf2e1 Set CXX standard 2026-10-25 18:15:35 +03:00
48a8720ba8 Fix some compile warnings 2026-10-25 18:08:23 +03:00
dacdd9e8d3 Print vitastor-cli help for ls-osds and user-modify aliases (#104)
vitastor-cli accepts ls-osds and user-modify, but --help does not list
them, so "vitastor-cli --help ls-osds" printed "Unknown command". Add
them to the help and to the docs, which also lacked the pgs alias in the
Russian version. Test that --help knows every name the CLI accepts.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-10-25 17:22:42 +03:00
5a6343f21d Refuse an invalid --resize value in vitastor-cli modify (#98)
parse_size() returns 0 for a value it cannot parse, such as 1.5G, and
modify took 0 as "no resize": it printed "No change" and exited with 0.
Check the parse result and fail with EINVAL, as create does for --size.
Numeric sizes passed by internal callers (NFS, dd) parse as before.

Tested: new tests/test_modify_image_resize.sh (`--resize 1.5G`, `10X`, `abc`, empty), fails without the fix and passes with it.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md

Co-authored-by: Yury Luneff <koolkhel@mail.ru>
Co-committed-by: Yury Luneff <koolkhel@mail.ru>
2026-10-25 17:20:17 +03:00
c4359a4a8d Fix missing space in vitastor-cli rm-osd "still up" message
rm-osd printed "OSD 1is still up" and "OSDs 2, 3are still up" because
the verb was appended to the OSD list without a space. Also say "it"
instead of "them" when only one OSD is up.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 17:18:02 +03:00
d3e708dd8d Fix vitastor-cli osd-tree crash when the etcd request fails (#100)
load_osd_tree() stored the etcd error, but loop() still called
format_tree() which dereferenced the placement tree that was never
built, so osd-tree and ls-osd died with SIGSEGV. Return the error
instead.

Tested: no automated test, the test harness cannot fail just this one etcd request. Reproduced with a failure-injecting HTTP proxy in front of etcd: osd-tree and ls-osd exit with 139 (SIGSEGV) before the fix and print the etcd error with EIO after it.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 17:15:23 +03:00
d775042a36 cli/dd: Read a character device input like a pipe
A character device reports st_size 0, so one that supports lseek (e.g.
/dev/mem or an MTD device) was taken as an empty seekable input and dd
always failed with "Input seek position is beyond end of input". Treat
every character device input as non-seekable with unknown size and read
it up to count=, size= or its end. /dev/zero and /dev/urandom don't
seek and were already read this way.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 17:13:55 +03:00
Arsenii Ermilov
303c602ea5 cli/dd: Free the skip buffer when reading the input fails
skip_read() returned on a read error or EOF without freeing the buffer
it allocated, leaking it once per failed dd.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 17:13:14 +03:00
c159b9019d Correct vitastor-cli help for rm, raw-ls, fix and rm-osd
- rm: the --exact and --matching descriptions were swapped.
- raw-ls: show that --pool_id is required, and --pg_num unless --offset
  is given, and when the pool configuration fills in the rest.
- fix: show --bad-osds as required.
- rm-osd: describe -f, --allow-up and --allow-data-loss. Up OSDs are
  refused too, -f covers them and degraded/offline PGs, and
  --allow-data-loss covers incomplete ones and implies -f.

Apply the same corrections to the CLI documentation.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 17:13:00 +03:00
cd2ccf9f37 Merge tests to test_modify_pool 2026-10-25 16:14:44 +03:00
4b5442e84c Limit pg_size to 64 in vitastor-cli create-pool and modify-pool
The CLI accepted pg_size up to 256, but clients and OSDs skip a pool
with pg_size > 64 and the monitor refuses it, so such a pool was
created or switched to a size nobody could serve, without an error.
Refuse pg_size > 64 with EINVAL, also with --force.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:13:19 +03:00
32421ed404 Allow to remove level_placement with an empty modify-pool value
An empty --level_placement was dropped before the merge with the old
pool config, so the old rules stayed and could not be removed at all,
and a malformed value was silently dropped the same way. Make an empty
value remove the key, which the monitor treats as no extra rules, and
refuse a value that is not <level>=<rule>[,...] with EINVAL.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:12:51 +03:00
8ef4e7db93 Refuse renaming a pool to the name of another pool in vitastor-cli
modify-pool --name did not check the new name against other pools, so
two pools could end up with the same name, and commands addressing a
pool by name then picked either of them. Fail with EEXIST, as
create-pool does. The check uses the pool list that the CAS write is
based on, so a concurrent rename or create is caught by the retry.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:11:55 +03:00
beef3d64df cli/dd: Check write alignment before creating the output image
The "Unaligned write to Vitastor is not supported" check ran after the
output image was created or resized, so a seek= or bs= not aligned to
the pool's bitmap granularity failed with EINVAL but left a new or
resized image behind. Check it as soon as the granularity is known.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:08:28 +03:00
f308a54fb5 cli/dd: Copy a pipe input to its end when no count= or size= is given
With a non-seekable input and no count= or size=, read_end stayed 0, or
was capped at zero bytes by out_size defaulting to seek=, so dd stopped
after the first block: "cat file | vitastor-cli dd of=copy" copied 1 MB
and exited 0. Leave read_end unlimited then and default out_size only
when the input length is known. A new or truncated image still needs
size=; conv=trunc on a file still truncates it at the seek offset.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:08:05 +03:00
9684e1afb3 cli/dd: Fix oflag=append
oflag=append replaced O_RDWR with O_APPEND, so the output file was
opened read-only and every write failed with EBADF. Open it with
O_WRONLY|O_APPEND. An appending output is not seekable, which also
skipped the final fsync: skip it only for outputs that can't be synced
(anything but regular files and block devices). Refuse conv=trunc with
oflag=append, the two contradict each other.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:05:38 +03:00
911a79f03b cli/dd: Implement status=noxfer
status=noxfer is listed in the help, but dd ignored it. Make it drop
the final transfer statistics like in GNU dd. The progress line still
follows --progress and, if it was shown, is cleared at the end instead
of being replaced by the statistics. --json still returns them.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 16:05:24 +03:00
ddb699c5e8 cli/dd: Make status=none also suppress the progress output
status=none only dropped the final statistics when --progress 0 was
also given; with the default --progress 1 dd still printed the progress
line and the statistics. Turn progress off with status=none, so only
errors are printed, like in GNU dd. --json still returns the result.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 15:55:50 +03:00
d2b879098d cli/dd: Detect input size also when size= is given
size= turned input size detection off, so dd from an image, a file or a
block device with size= always failed with "Input seek position is
beyond end of input", after the output image was already created or
resized. Always detect the input size: size= only sets the output size.
Also check the input seek position before opening the output.

I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-25 15:55:34 +03:00
a83a0aed07 Store v2: Do not take a data fsync slot for redirect_intent writes
Since 0c888845 every big write with data fsync enabled takes a slot in
data_fsyncs, but only big_writes mark theirs completed, redirect_intent
writes skip the data fsync. Their slot stays forever and every later
big_write waits for it, so after the first stable write to a new object
all unstable big writes of the OSD hang.
2026-10-19 15:55:41 +03:00
357dab2c5c Store v2: Skip zero-sized entries during recheck, part 2 + test 2026-10-18 10:43:58 +03:00
2be4191e55 test_pg_chaos fixes
- demote acked versions only when the client session dies
- release wire stragglers at the end of a run
- take pg history epoch from etcd, not from the OSD's st_cli view
2026-10-18 02:00:12 +03:00
f3b80e0e6c Run make.js on docs 2026-10-17 21:31:47 +03:00
Changwei Ye
4d34da9483 osd: fix degraded check in add_object_to_set on replicated pools
In replicated pools, all replicas have role 0, so n_roles is set to 1
as long as at least one healthy copy exists. Comparing
n_roles < pg.pg_cursize was therefore always true for multi-replica
pools (e.g. 1 < 3 or 1 < 2), incorrectly marking healthy objects as
OBJ_DEGRADED and shadowing the OBJ_MISPLACED check below.

Conversely, directly using n_copies is also insufficient because
n_copies includes corrupted copies (n_corrupted). If a replica is
corrupted, n_copies remains equal to pg_cursize, preventing the object
from being marked as OBJ_DEGRADED and leaving it unrepaired.

Fix this by using (n_copies - n_corrupted) for replicated pools to count
only healthy copies, ensuring accurate degradation detection and
recovery.
2026-10-17 21:23:36 +03:00
Changwei Ye
8dd76839f1 osd: call deref_object_state on recheck_state mismatch in remove_object_from_state
When recheck_state != *object_state, the old object_state reference should be
released via deref_object_state() instead of raw ref_count--. Otherwise, if the
old state has no remaining objects (object_count == 0) and this was its last
reference, it would never be erased from pg.state_dict, leaking memory and state
dictionary entries.
2026-10-17 21:21:34 +03:00
Changwei Ye
bba9aacfe3 osd: use lower_bound to find head operation in pg_cancel_write_queue
std::multimap::find() is not guaranteed by the C++ standard to return the
first element of a range with equivalent keys, which may fail to retrieve
the head operation in pg.write_queue.

Switch to lower_bound() to reliably locate the head of the queue in O(log N)
time, and add an explicit check for it->first == oid to prevent falsely
matching a subsequent larger key when the target oid is missing.
2026-10-17 21:20:35 +03:00
e11d3afb22 Release in-flight OSD-owned operations when the OSD dies 2026-10-17 20:19:02 +03:00
cd06495a2d Shut down OSD peer sockets before closing them in stop_client
I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
2026-10-17 20:15:20 +03:00
df8b7d3aff Add rdma_traffic_class, rdma_sl and rdma_set_flow_label options 2026-10-17 20:15:20 +03:00
7614031995 Check read access to parent image when creating a clone 2026-10-17 20:15:20 +03:00
21f188d64c Do not clear Vault keys on pool reconfiguration, reload after vault_error_timeout_sec on errors 2026-10-17 20:15:20 +03:00
5decb9d910 Fix inode vault_key loading for parent images 2026-10-17 20:15:20 +03:00
5fc210aa0e Drop dead instance's in-flight ring IOs from disk simulation on crash
Without it, disk bytes get copied into freed buffers and reused ring
slots complete with stale callbacks.
2026-10-17 20:15:20 +03:00
daba5f02bb Keep completed ops visible to run_until predicates in test_pg_chaos 2026-10-17 20:15:20 +03:00
30a90e5824 Store v2: Skip zero-sized entries in metadata recheck instead of issuing zero-sized reads 2026-10-17 12:34:02 +03:00
8ad9131303 Deliver etcd mock callbacks via ringloop to avoid reenterability issues 2026-10-17 00:49:42 +03:00
38e79f7f54 Do not always settle() PG after restart in pg_chaos 2026-10-16 18:52:09 +03:00
4404e18092 osd: fail writes waiting for a flush when their PG stops being active
A write to an object with pending flush_actions waits at the head of
the write queue until a flush batch succeeds, but flushes only run for
active PGs. If the PG repeers or stops first (a peer dies during the
flush, the flush fails, or the PG repeers between two flush batches),
the write keeps inflight and the PG hangs in REPEERING or STOPPING
forever. A flush error on an already stopping PG restarted peering
under the queue and hit the assert in reset_pg.

Fail such writes with EPIPE when the PG leaves the active state,
so clients retry them after peering, and let a stopping PG finish
its stop instead of peering again.
2026-10-16 18:51:02 +03:00
0be24276e5 Make _intervals uint64 2026-10-16 18:46:04 +03:00
e24488de63 Fix memory leaks in test_pg_chaos 2026-10-16 17:41:20 +03:00
3cf04530df Store v1: Fix exotic hang on an unflushable deletion (test_blockstore_chaos --seed 10901878)
Co-Authored-By: Yury Luneff <koolkhel@mail.ru>
2026-10-15 01:33:51 +03:00
15c31260a5 Implement single-PG OSD-side logic chaos test 2026-10-14 01:21:35 +03:00
2e223f03e4 Client: Make SYNC/write-repeat correct to avoid losing buffered data
Two problems are fixed:
1) PG configuration may be already changed at the moment of a peer crash so
   it's incorrect to use it for the affects_osd() check. Save the written_to OSD
   number explicitly instead.
2) Sync did not return dirty_osds back into the set on a failure, so it wasn't
   repeating correctly.

Before this fix, test_heal was sometimes flapping in CI. Now it should become stable.
2026-10-14 01:21:35 +03:00
eac58a17a7 Remove test_shit 2026-10-14 01:21:35 +03:00
0d35d83585 Use osd_num_t for the OSD number in most places 2026-10-14 01:21:35 +03:00
2316d36840 Support multiple etcd_state_client mocks over the same store 2026-10-14 01:21:35 +03:00
368daa4b1e osd: Accept unstable EC versions on peering only if full to avoid INCOMPLETE on subsequent OSD crashes 2026-10-14 01:21:35 +03:00
d16423bb85 osd: forget PG unstable writes on stop/repeer_pg so SYNC can't commit fragments peering will roll back 2026-10-14 01:21:35 +03:00
2eb072ecbf osd: make reads that hit ENOENT from a racing op wait in the write queue instead of failing as corrupted 2026-10-14 01:21:35 +03:00
ee47e3b0c3 osd: serialize primary delete and SYNC stabilize, forget unstable versions on delete 2026-10-14 01:19:54 +03:00
3c0284d134 OSD: support clean osd_t object destruction 2026-10-14 01:17:22 +03:00
Changwei Ye
45ce3f2842 osd: account for key_index_bytes when calculating chained read bitmap_len
When OSD_OP_RETURN_CHAIN is set, the primary OSD appends chain info to
the returned bitmap buffer. The space required for chain info is
(len / bs_bitmap_granularity) * key_index_bytes, where key_index_bytes
depends on the snapshot chain depth (1 byte for <= 255 items, 2 bytes for
<= 65535, etc.).

Previously, cur_op->reply.rw.bitmap_len only added (len / bs_bitmap_granularity)
without multiplying by key_index_bytes. When the snapshot chain depth
exceeded 255 (key_index_bytes == 2), the reported bitmap_len was too short,
causing the client to receive truncated chain info.

Multiply by key_index_bytes when updating cur_op->reply.rw.bitmap_len, and
add test_chained_read_large_chain_info regression test in osd_test.
2026-10-09 17:18:32 +08:00
b1fd754832 osd: don't let PG epoch regress below the value persisted in etcd 2026-10-04 18:32:21 +03:00
68ade43e70 osd: reset read ranges and degraded state before a primary read retry 2026-10-03 15:34:11 +03:00
c64528eb80 Store v2: Do not restart LSN allocation below the persisted completed_lsn 2026-10-03 14:18:27 +03:00
7bac25cbed Store v2: do not crash on incorrect chains with all entries between delete and commit lost 2026-10-03 10:40:35 +03:00
771a73c181 Store v2: do not crash on add_commit over a fully rolled back chain 2026-10-03 10:40:35 +03:00
f830b693db osd: count stale copies on an OSD holding another role as outdated 2026-10-03 10:40:35 +03:00
9953ca366c osd: initialize statistics counters read before first assignment
prev_stats/prev_report_stats, report_stats_ts, the recovery stat pairs and
rtune_prev_stats were read on the first reporting cycle before ever being
written; valgrind reported conditional jumps on uninitialized values.
report_statistics() also checked tv_now.tv_sec for zero before assigning it.
2026-10-02 16:59:25 +03:00
c0afde8989 osd: don't report PG states before the lease is acquired
PG init can complete before acquire_lease() when blockstore init is
asynchronous. Early state puts wrote lease 0 into the PG state key, after
which the lease check of every subsequent CAS fails forever: the OSD kept
printing 'Error reporting PG 1/1 states' and the PG could never peer.
Skip reporting until the lease exists and flush held-back reports right
after it's granted.
2026-10-02 16:59:25 +03:00
376237bc6a Store v2: fix incorrect small_writes over a chain rolled back to 0 2026-10-02 16:59:25 +03:00
9c2ee9d6ba Make delete of a non-existing object a successful no-op 2026-10-02 16:59:25 +03:00
00f42b4b79 Record new copies of misplaced objects after partially failed writes
mark_partial_write() only walks the object's current location set. A
write to a misplaced object goes to the PG's target set, so an OSD of
the target set that didn't have the object before can take the new
version without being in that set, and such a copy was never recorded.

For example, in a replicated PG with target set 1, 2, 3 an object may
still be on OSD 1, 2 and 4 from the previous set. If a write fails with
ENOSPC on OSD 1 and 2 and succeeds on OSD 3, OSD 1, 2 and 4 are marked
outdated and OSD 3 isn't added. No current copy is left, so the object
becomes incomplete, and reads and partial overwrites fail with EIO until
the PG is re-peered, although OSD 3 has the new version. If only OSD 1
fails, the object is left with one recorded current copy instead of two.

This is the same problem as fixed in 75a35c3b ("Unmark previous partial
writes on a repeated partial write to a different OSD"), but for OSDs
which aren't in the object's location set.

Add OSDs where the write succeeded to the set if they aren't there
yet. The set of a clean object is built from the PG's current set and
already has all of them, so nothing changes for clean objects.
mark_partial_write() is only used for replicated pools, so new copies
get role 0.

Also add a regression test, test_partial_write_to_misplaced_object.
2026-10-02 16:59:25 +03:00
bf33844740 Fix QEMU driver build for idiotic RHEL backport into 9.1 2026-10-02 16:59:25 +03:00
1094f1b370 Fix error handling in the transport encryption handshake
- Check the result of EVP_KDF_CTX_new() in msgr_handshake_ctx_t::init().
- Check the created cipher context instead of msgr_handshake_t::ctx
  after EVP_CIPHER_CTX_new() in encrypt() and decrypt().
- Set the error message and the error state when the handshake signature
  is invalid, and clear the OpenSSL error queue so that its errors are not
  reported by the next on_error() call.
2026-10-02 16:59:25 +03:00
d09a72fbbc Fix stale HKDF salt after transport encryption key rotation
Some OpenSSL 3 versions ignore empty OSSL_KDF_PARAM_SALT in HKDF (checked:
3.0.0, 3.0.13, 3.0.14, 3.3.0, 3.3.3, 3.4.0, 3.5.0; 3.0.19 and 3.5.4 are
fixed). So the shared kdf_ctx kept the salt set by the last key rotation
(derive_aes_keys uses the old key as salt), and all following derive_kdf
calls without salt, i.e. handshakes of all new connections, derived keys
different from the peer's and failed with "Handshake decryption failed"
until restart.

Reset the context before each derive_kdf call.

Add test_msgr_kdf with HKDF-SHA384 known-answer vectors, including a call
without salt after a key rotation.
2026-10-02 16:59:25 +03:00
f3e047fb05 Store v2: fill the checksum slot of zero-length small writes
get_small_entry_size() always reserves a 4-byte data checksum slot when
block checksums are off, and the entry-level checksum covers every byte
of that size - but get_checksum() returned NULL for small/intent entries
with len == 0, so calc_checksums() skipped the slot and the entry
checksum was computed over whatever malloc leftover bytes happened to be
there.
2026-09-29 01:40:00 +03:00
df593badb5 Release 3.2.2
- New store (thanks Changwei Ye)
  - Fix rejected compaction when an object is already overwritten again
  - Reduce superblock I/O amplification introduced after previous correctness fixes
- Fix possible `vitastor-cli rm` crash with `assert(rwo->todo == 1)` introduced in 3.2.1
- Fix replicated objects possibly incorrectly transitioning to the INCOMPLETE state
  after multiple failed partial writes
- Fix possible "operation sequencing broken ... expected num 2, got 3, stopping client"
  possible when a cluster is overloaded by peering/OSD flaps
2026-09-27 14:29:43 +03:00
Changwei Ye
b51c05200d Store v2: fix compaction skipping stable overwrites and BIG_INTENT type
The original compaction condition only postponed compaction when not under
pressure, and only for BIG_WRITE and DELETE types:
  if (!under_pressure && (BIG_WRITE || DELETE))
This had two bugs:
1. BIG_INTENT overwrites were not included, causing add_compact() to be
   called on BIG_INTENT entries. add_compact() unconditionally rejects
   any stable overwrite with EBUSY, leading to unnecessary retry loops.
2. When under pressure, stable overwrites (BIG_WRITE, BIG_INTENT, DELETE
   with BS_HEAP_STABLE set) were not skipped. add_compact() rejects stable
   overwrites with EBUSY regardless of pressure, so attempting to compact
   them under pressure also always fails.
Fix: change the condition to:
  if ((!under_pressure || stable) && (BIG_WRITE || BIG_INTENT || DELETE))
When under pressure with an unstable overwrite, we now fall through to
`continue`, skipping it and scanning older entries (SMALL_WRITE /
INTENT_WRITE) that can actually be compacted to reclaim space.
2026-09-24 17:06:20 +08:00
6d1b9165a2 Store v2: decouple trim_lsn from force_fsync
Commit df9a2850 introduced force_fsync to resolve the placement contract
conflict (EAGAIN) when a new metadata entry depends on a previous unsynced
entry that is already in-flight. However, it mistakenly grouped the
'force_fsync > 0' condition together with the Superblock Checkpoint logic.

As a result, every time the internal torn-write prevention mechanism
requested a force_fsync, the system inadvertently executed an expensive
trim_lsn() (updating the Superblock with RWF_DSYNC), causing unnecessary
write latency and I/O amplification during congested object updates.

This change minimally refactors the state machine to ensure trim_lsn() is
strictly bound to the intended journal_trim_interval, while force_fsync
only triggers the necessary fsync_buffer().
2026-09-24 11:08:15 +03:00
e58b37b284 Fix CAS merge assert(rwo->todo == 1) 2026-09-23 00:04:01 +03:00
53c7da3e2d %lu -> %ju, peer_fd -> client_id in one log message 2026-09-21 01:10:31 +03:00
75a35c3b36 Unmark previous partial writes on a repeated partial write to a different OSD 2026-09-20 00:32:50 +03:00
a375f43a93 Fix possible "operation sequencing is broken on client XX: expected num 2, got 3, stopping client" during shitstorm :] 2026-09-19 21:29:47 +03:00
22ae66b95f Now fix build with qemu < 8 :D 2026-09-13 12:39:31 +03:00
456fad7fa7 Add opool to docs 2026-09-13 12:13:06 +03:00
06a5d24240 Release 3.2.1
- Blockstores
  - Add more asynchrony to the chaos test to uncover more issues...
  - ...and fix them (~6 in the old store, ~9 in the new store)
  - Fix size check for journal_offset when sharing meta device (thanks Changwei Ye)
- Network layer
  - Correctly handle out-of-order zero-copy notifications (rare but possible in theory)
  - Fix double checksumming of header in proto_checksums=full mode
  - Add rxbounce option for Windows guests with TCP and enabled checksums
  - Close stopped peer sockets early to prevent hung zerocopy notifications and slow failover (~15 min instead of ~10 sec)
- OSD
  - Do not die on local blockstore modification errors (irrelevant since added write error handling)
- CSI
  - Fix VitastorFS NFS daemon lifecycle (thanks Dmitry Naumov)
  - Use a newer qemu-storage-daemon in CSI
- vitastor-cli
  - Add `dd` opool option
  - Fix `rm` with "inverse" optimisation incorrectly removing layer data before rename
    possibly leading to incorrect reads from child images during removal of an older-than-latest snapshot
  - Fix a possible hang in `merge` and derived commands (`rm`, `flatten`)
  - Fix mistakes in the `serve` OpenAPI spec (thanks Stepan Rabotkin)
  - Fix possible segfaults in `serve` due to invalid request parsing (thanks Vincent Schweiger)
  - Fix `serve` no-HTTPS mode (thanks both :))
- Build
  - Fix non-x86 builds failing due to unsupported xxhash x86dispatch
  - Forcibly enable assertions in all builds to remove build profile dependency
  - Fix QEMU driver build with QEMU < 10.2
2026-09-13 11:11:12 +03:00
a6a99a5967 Close sockets to prevent hung zerocopy notifications - with surrogate client IDs it's safe now 2026-09-11 02:05:08 +03:00
eba8ca7192 Add rxbounce option for Windows guests 2026-09-11 02:04:56 +03:00
Dmitry Naumov
e1d9121870 Fix VitastorFS NFS daemon lifecycle in CSI 2026-09-11 00:46:57 +03:00
72620ebee5 Store v1: Make sync wait for deletions which erase unsynced writes
Found by test_blockstore_chaos --seed 1487 and 534428711
2026-09-09 10:07:04 +03:00
d0e3ee4c2a Store v2: Repeat recheck for entries behind a dropped BIG_INTENT
The following sequence is possible:
big_write - small_write (unfinished) - big_intent (unfinished)

In this case we should recheck both overwrites. But we can't just always recheck
small_writes before big_intents because they're garbage if the big_intent is finished.
So recheck them only if the big_intent itself is marked as unfinished and dropped.

Found by test_blockstore_chaos --seed 165428650 and 214734465
2026-09-09 10:02:46 +03:00
328bf0cba1 Store v2: Don't skip checksums for unfinished overwrites during recheck
Found by test_blockstore_chaos --seed 370644250
2026-09-09 10:02:17 +03:00
16ce85d685 Store v2: Do not allow intent writes over unfinished compaction big_write
Found by test_blockstore_chaos --seed 1034655488
2026-09-09 10:00:45 +03:00
606dd820cd Store v2: Fix compaction versions on repeated commits with unstable entries between them
big v1 -> small v2 -> commit v1 -> small v3 -> commit v2 was writing a compaction entry
with version=1 but with v2 actually compacted in it.

Found by test_blockstore_chaos --seed 255885411
2026-09-09 10:00:13 +03:00
f9f0b35311 Add vitastor-cli dd opool option 2026-09-08 00:56:21 +03:00
778a3469b4 Fix double checksumming of header in proto_checksums=full mode 2026-09-08 00:25:12 +03:00
a8ed25ddf5 Store v1: free dyn_data when WRITE_STABLE over WRITE is refused
Signed-off-by: Yury Luneff <koolkhel@mail.ru>
2026-09-07 00:39:14 +03:00
49877a0fa9 Fix too long osd_peering_pg test output 2026-09-07 00:37:03 +03:00
4e11fd256e Fix printing make_test errors in CI on failure 2026-09-06 21:04:03 +03:00
1a1c338cc9 Clear write_op/write_ops in client destructor 2026-09-06 18:29:10 +03:00
7f88846a5d Replace send_free_ops + zc_free_list with a single send_free queue, handle out-of-order zerocopy completions correcty 2026-09-06 18:29:10 +03:00
d5f1f6967a Fix uninitialized op_enc 2026-09-06 18:29:04 +03:00
c486a14f6a Use vector ring_datas and free_ring_data in ringloop
(Also fixes cleanup of callbacks still queued on destruction)
2026-09-06 16:53:07 +03:00
df3c8cf72b Do not die on local blockstore modification errors 2026-09-06 16:53:07 +03:00
a8f5d7cafe Disable output buffering in test_cas 2026-09-06 14:50:25 +03:00
c5efed2061 Silence build warnings in std::regex 2026-09-06 14:09:04 +03:00
d5e56827c7 Print test_chaos output on failure 2026-09-06 11:24:03 +03:00
a788add518 Return EBUSY on ROLLBACK when already stable, like in the new store 2026-09-06 11:24:03 +03:00
d5ebc93e7d Add libvirt patch for 11.10 el10 2026-09-05 21:02:51 +03:00
9d4067bcf0 Add spec patch for qemu 10.1 el10 2026-09-05 20:37:19 +03:00
0be4cba1e6 Fix QEMU driver build with QEMU < 10.2 2026-09-05 20:06:52 +03:00
2179f6ab55 Use a newer QSD in CSI and fix CSI build 2026-09-05 17:46:35 +03:00
1dd4cbd7c3 Store v1: Fix deadlock when trying rollback a committed write (fuzzing) 2026-09-05 15:24:36 +03:00
174b36cf46 cli/rm: Move children of "inverse child" before removing its data 2026-09-05 14:32:29 +03:00
eb6328d443 Make test_chaos run 48 fixed seed + 152 random seeds by default 2026-09-05 11:25:58 +03:00
c560f3883d Store v1: Join an already-write-scheduled sector when appending to it 2026-09-05 10:56:47 +03:00
4d96f73738 Store v2: Fix crc32_iter: "data != NULL" assertion failed on intent write block checksum compaction 2026-09-05 10:56:47 +03:00
7cbdd831c7 Store v1: Make only the operation original writing a journal sector release its flush_count 2026-09-05 10:56:47 +03:00
820a226b1d Store v1: Fsync all devices on start 2026-09-05 10:56:47 +03:00
a25625a1d3 Store v1: Forget big_writes already taken by sync, but only after waiting for that sync 2026-09-05 10:56:47 +03:00
db0b6ec926 Store v1: Make sync wait for all previous syncs 2026-09-05 10:56:47 +03:00
097afe5d8b Store v2: Fix another source of "double-claimed" blocks due to ABA when freeing big_write blocks 2026-09-05 10:56:47 +03:00
fbf48a86be Store v2: Recheck writes under commit/rollback too (fsync is only done after the commit)
We could fsync before commit/rollback, like in the old store, but it works this way too
2026-09-05 10:56:47 +03:00
2cb32f704d Store v2: Fix interrupted compaction with big_intent base with disabled checksums 2026-09-05 10:56:47 +03:00
d397d7ac3e Store v2: Do not allow parallel superblock updates for stricter disk semantics 2026-09-05 10:56:47 +03:00
9d36831ae7 Store v1: Track inflight reads in a map to allow clean destruction without leaks in tests 2026-09-05 10:56:47 +03:00
85976c2f31 Store v2: Track inflight reads in a map to allow clean destruction without leaks in tests 2026-09-05 10:56:47 +03:00
517c016324 Rework test_blockstore_chaos to a fully asynchronous loop to uncover more bugs 2026-09-05 10:56:47 +03:00
Vincent Schweiger
2b5078823a Fix HTTP API segfault with empty URI 2026-09-05 10:51:01 +03:00
Vincent Schweiger
b2d5206613 Fix unnecessary HTTP API request headers map insertion 2026-09-05 10:51:01 +03:00
Vincent Schweiger
c67843e6b5 Fix HTTP API segfault with malformed HTTP request 2026-09-05 10:51:01 +03:00
Vincent Schweiger
9353a58446 Fix HTTP API URI out of bounds array access 2026-09-05 10:51:01 +03:00
7e0ba6d312 Forcibly remove NDEBUG from everywhere :) 2026-09-05 00:57:58 +03:00
beb7854e39 Fix todo tracking in merge 2026-09-05 00:38:37 +03:00
4d567dd0e6 Disable xxhash dispatch when building for non-x86 2026-09-05 00:38:36 +03:00
ye.changwei
4b95d248bf fix: logic error in boundary check for "exactly two partial blocks" during read request merging
When a read request is expanded outwards to align with checksum boundaries, `blk_end` becomes a
multiple of `csum_block_size`. The original code used `blk_end/dsk.csum_block_size ==
blk_start/dsk.csum_block_size+1` to determine whether this request with padding crosses exactly two
checksum blocks. However, since `blk_end` perfectly aligns with the physical boundary, the division
here will inevitably cause a carry, rendering the condition invalid. This incorrectly caused the
engine to split an I/O that should have been issued at once into multiple separate I/O requests,
increasing unnecessary memcpy overhead.

For example, in a real scenario (32KB csum_block_size):
- User reads logical range 28KB ~ 36KB (start=28672, end=36864). The write record (wr) spans 16KB ~
  64KB, so the initial logical clipping leaves start and end unchanged.
- To verify checksum, the engine expands the physical boundary: blk_start=0, blk_end=65536.
- After the second MVCC record clipping on physical boundaries, the effective read boundary of the
  physical data is 16KB ~ 64KB (blk_start=16384, blk_end=65536).
- Physically, these are exactly two adjacent partial blocks (16K~32K and 32K~64K, with padding waste
  at both ends). For performance, they should be read in a single I/O.
- But the original code executed: `65536/32768 (i.e., 2) == 16384/32768 (i.e., 0) + 1`, evaluating
  to `2 == 1` (False).
- As a result, this read was sub-optimally split into two independent I/Os (16K~32K and 32K~64K).

Fixing the condition to `(blk_end-1)/dsk.csum_block_size` accurately finds the block that actually
contains the last valid byte, restoring the expected read merging behavior of this branch and
avoiding breaking the zero-copy fallback optimization.
2026-09-05 00:17:39 +03:00
cee6882d6e Fix size check for journal_offset when sharing meta device
When journal_device and meta_device share the same device, but they
are separate from data_device (e.g., Data on HDD, while Meta and Journal
are on a shared NVMe SSD), the boundary check for journal_offset incorrectly
compared the offset against data_device_size.

This could lead to out-of-bounds I/O on the NVMe SSD if the configured
journal offset was larger than the SSD but smaller than the HDD, or it
could cause false-positive startup failures if the HDD was smaller than
the NVMe SSD.

This fix ensures that journal_offset is appropriately checked against
meta_device_size when it is available (i.e., when meta and data are on
different devices), and falls back to data_device_size only when all
three share the same physical device.
2026-09-05 00:16:45 +03:00
5c45425235 fix(openapi): rename ImageListParams.globs to names
/image/list is served by ls, which reads cfg["names"]
(src/cmd/cli_ls.cpp:597). Nothing reads "globs", so the documented
filter was accepted and silently ignored.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 20:28:16 +03:00
dd9b9f926d fix(openapi): drop the leftover format and description on two OSD schemas
The 200 schemas of /osd/delete and /osd/modify are objects but carried
"format": "uint64" and "description": "New OSD number" at schema level,
copied from /osd/alloc where the response really is a number.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:57:33 +03:00
806ebf5bcd fix(openapi): describe every response
Added description to the 30 responses that lacked it: the 200 of every
operation and the inline 412 of /osd/delete and /data/delete. OpenAPI 3.0
requires it.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:57:33 +03:00
5f4e394eb0 fix(openapi): drop the Swagger 2.0 consumes and produces leftovers
Removed 48 occurrences. OpenAPI 3.0 has no such fields and the media
types are already declared in requestBody.content and responses.*.content.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:57:33 +03:00
50e36a04df fix(openapi): add the required info.title field
OpenAPI 3.0 requires info.title. Reuses the text of info.description.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:57:03 +03:00
9fc2781798 fix(openapi): require image, not the undefined names, in /image/flatten
The schema required "names", which it does not define. The handler reads
cfg["image"] (src/cmd/cli_flatten.cpp:141).

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:57:03 +03:00
26c6251888 fix(cli): create an http context when serving plain HTTP
http_ctx was assigned only in the TLS branch, so on plain HTTP it stayed
NULL and http_init() segfaulted on the first accepted connection.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:43:19 +03:00
145942fc3c fix(openapi): give /osd/modify and /data/fix unique operationIds
Duplicate operationIds are forbidden outright by the OpenAPI
specification: the field must be unique among all operations in the
document. Two endpoints violated it by carrying the id of their
neighbouring delete operation, most likely copy-paste leftovers:
/osd/modify was osdDelete and /data/fix was dataDelete.

Rename them to osdModify and dataFix. Client generators derive method
names from operationId, so besides restoring validity this stops the
duplicates from silently colliding or being renamed by the generator.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-02 19:39:30 +03:00
2a68ad2a05 fix(openapi): fold the enc_key oneOf into a single string
The two string branches of enc_key carry no discriminator, so a decoder
cannot tell them apart. They do not overlap, so each union becomes one
string whose pattern accepts the same values.

Signed-off-by: Stepan Rabotkin <epicstyt@gmail.com>
2026-09-01 22:40:43 +03:00
10a6782bdf Fix compilation errors regarding type conversions and pointer arithmetic
- src/blockstore/v1/init.cpp: Add explicit uint32_t cast to fix narrowing conversion error when initializing dirty_entry state.

- src/client/msgr_receive.cpp: Cast void pointer (iov_base) to char* before performing pointer arithmetic.
2026-08-31 18:44:21 +08:00
5f2b46bb57 Fix misleading COPY_BUF_JOURNAL flag on hole slices
During compaction (`fill_partial_checksum_blocks`), when a partially overwritten
checksum block is encountered, the old data needs to be read from the base layer
(`clean_wr`). A coalesced slice is inserted into `read_vec` to logically reference
this base block data.

Previously, this coalesced slice was marked with `COPY_BUF_JOURNAL`. This is a
misuse of the flag because the underlying data originates from the data area (a
BIG_WRITE block), not the journal area. It should conceptually use `COPY_BUF_DATA`.

Although this misuse did not cause any functional bugs—because the coalesced slice
also carries the `COPY_BUF_COALESCED` flag, which perfectly short-circuits the I/O
submission in `read_buffered` and avoids erroneously reading from `journal_fd`—it
creates semantic confusion for future maintainers. `COPY_BUF_JOURNAL` is consistently
used elsewhere to denote small writes (journal data).

This commit changes the flag to `COPY_BUF_DATA` to ensure semantic correctness and
code self-consistency.
2026-08-31 18:44:19 +08:00
f9a247df42 Release 3.2.0
Read more at https://vitastor.io/blog/2026-08-31-v3.2.0.html

- Add a DST-style chaos test for both blockstores and fix a large number of problems uncovered with it.
- Implement online resize for ublk, NBD, QEMU and VDUSE, and CSI.
- Add VitastorFS mount helpers.
- Allow to configure NFS `--readahead`.
- Allow to use the client without io_uring again (`use_sync_send_recv`) - with RDMA it's just as fast.
- Add a `/healthcheck` handler to the monitor.
- Handle SIGINT and SIGTERM in NBD, ublk and NFS servers.
- Prevent infinite blocking of the blockstore operations - retry with `EAGAIN`.
2026-08-31 02:02:34 +03:00
6f55e36998 Check bitmaps in the chaos test 2026-08-30 23:54:14 +03:00
1cbe466c39 Store v1: Use entry_fits in deletes (fix assertion failed at v1/journal.cpp:148) 2026-08-30 19:31:41 +03:00
38a0a9b9b7 Store v1: Fix a memory leak in split stabilize/rollback ops 2026-08-30 19:31:14 +03:00
c826cbb735 Store v1: Fix rollback over unsynced write hang 2026-08-30 19:31:13 +03:00
6038c537da Add configurations without checksums to the chaos test 2026-08-30 19:29:46 +03:00
77481dd824 Store v2: Fix object with big_intent base possibly disappearing after restart
if compaction overwrites part of it but fails to write the updated metadata entry
2026-08-30 19:29:46 +03:00
9ff24abc0e Store v1: Forget unstable entries on delete, do not wait for them 2026-08-30 19:29:45 +03:00
c2dc2e5840 Add options and failure summary to the chaos test 2026-08-30 16:17:48 +03:00
df9a285019 Store v2: Fix possible loss of non-latest unsynced small_writes (non-capacitor drives)
Random part of the drive's write cache may be lost on failure so a newer write (say v3)
may reach the media but a previous one (say v2) may not. bs_heap doesn't chain metadata
entries so it may see v3 but without v2's changes in that case.

Fix it by requiring to write v3 into the same metadata block as v2, or do an additional
fsync before the second write if it's impossible.
2026-08-30 16:17:48 +03:00
a55cca724e Store v1: Fix possible "unexpected state during flush" for delete with a previous external sync 2026-08-30 16:17:48 +03:00
74c5047412 Store v1: Fix incorrect erasing of old entries during journal replay
resulting in "Fatal error: xxx was allocated over another write" errors
(introduced in 3fd779484d, not released)
2026-08-30 16:17:48 +03:00
157ef711d4 Change "There is a bug" comment to "There was a bug" :) 2026-08-30 16:17:48 +03:00
96983a4718 Fix zero-length memset on NULL (sanitizer issue) 2026-08-30 16:17:48 +03:00
1af744d1e3 Store v2: Recheck intent_writes written under small_writes too 2026-08-30 16:17:48 +03:00
db86731851 Remove detect_leaks=0 from CI 2026-08-30 16:17:48 +03:00
c14135cb7a Add atomic_write_size to the chaos test 2026-08-30 16:17:48 +03:00
cef3f16cca Do not pack shit into 64 bits 2026-08-30 16:17:48 +03:00
145c279f82 Add partial reads to the chaos test 2026-08-30 16:17:48 +03:00
d153583c7f Add rollbacks to the chaos test 2026-08-30 16:17:48 +03:00
0e9fe3a19f Store v1: Fix incorrect read_vec dyn_data refcounting memory leaks 2026-08-30 16:17:48 +03:00
ae8d47bffa Store v1: Add journal_flusher_co destructor (stop more memory leaks in tests) 2026-08-30 16:17:48 +03:00
2b25bb9488 Store v1: Free "our own" operations in the destructor (stop memory leaks in tests) 2026-08-30 16:17:48 +03:00
cb89e17255 Store v1: Fix division by zero with disabled checksums and disabled inmemory_journal 2026-08-30 16:17:48 +03:00
2ed098ea22 Store v1: Fix possible erroneous write of a non-modified journal sector, or even of a journal superblock 2026-08-30 11:35:55 +03:00
3cf7b1038e Store v1: Fix a possible hang: WAIT_DEL requests a flush, so guard it with request_trim() 2026-08-30 11:35:55 +03:00
87a57f577b Add trace mode to the chaos test 2026-08-30 11:35:55 +03:00
2233116023 Add object deletions to the chaos test 2026-08-30 11:35:55 +03:00
9a4b61424a Store v2: Fix on-read object data mutation check for intent writes 2026-08-30 11:35:55 +03:00
cde8f5b2c3 Store v1: do not re-submit a journal sector already written to (maybe not a bug but rather an UB) 2026-08-30 11:35:55 +03:00
d1bbb4578f Store v1: fix restart after a corrupted journal entry writing into skipped part of the journal 2026-08-30 11:35:55 +03:00
bdfc7349b9 Store v1: fix multiple journal write ordering 2026-08-30 11:35:55 +03:00
17a65f570d Store v2: fix write hang after restart without immediate_commit - restore fsynced_lsn 2026-08-30 11:35:55 +03:00
7bfe12a8f9 Free modified_blocks when blockstore is emergency destroyed 2026-08-30 11:35:55 +03:00
8f8b43d1d4 Add a simple blockstore v1/v2 chaos test 2026-08-30 11:35:55 +03:00
824762a04e Repeer PG on immediate stabilize/rollback errors 2026-08-30 11:35:55 +03:00
090c28c7c5 Return -EAGAIN from the new store when buffer area is full and unflushable, too 2026-08-29 18:03:18 +03:00
c35e101341 Return -EAGAIN from the old store when journal space is exhausted and flusher queue is empty to prevent blocking writes forever 2026-08-29 18:03:18 +03:00
230460e937 Deny "UB" OP_WRITE_STABLE over OP_WRITE in the old store 2026-08-29 18:03:18 +03:00
2a38d5d117 Store v1: free dirty dyn_data through the accessor that knows its layout 2026-08-29 18:02:57 +03:00
43d3d6560f OSD: Guard the chained-read inode lookup
prepare_primary_rw() looked the inode up for a chained read and
dereferenced the iterator without checking it
2026-08-29 16:54:03 +03:00
6d7223d9e9 OSD: Reject inverted ranges in DESCRIBE
Co-Authored-By: Yury Luneff <koolkhel@mail.ru>
2026-08-29 16:52:23 +03:00
238 changed files with 27391 additions and 2813 deletions

View File

@@ -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; \

View File

@@ -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

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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/ && \

View File

@@ -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/ && \

View File

@@ -1,4 +1,4 @@
VITASTOR_VERSION ?= v3.1.0
VITASTOR_VERSION ?= v3.2.3
all: build push

View File

@@ -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)"

View File

@@ -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)"

View File

@@ -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

View File

@@ -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

View File

@@ -8,7 +8,6 @@ import (
"encoding/json"
"fmt"
"strings"
"time"
"os"
"io/ioutil"

View File

@@ -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)
}
}

View 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
View File

@@ -1,4 +1,4 @@
vitastor (3.1.0-1) unstable; urgency=medium
vitastor (3.2.3-1) unstable; urgency=medium
* Bugfixes

View File

@@ -1,4 +1,4 @@
VITASTOR_VERSION ?= v3.1.0
VITASTOR_VERSION ?= v3.2.3
all: build push

View File

@@ -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}"

View File

@@ -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

View File

@@ -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

View File

@@ -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
- Тип: число

View File

@@ -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

View File

@@ -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
- Тип: целое число

View File

@@ -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: 'Можно менять на лету: да',
},

View File

@@ -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

View File

@@ -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

View File

@@ -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: \

View File

@@ -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: \

View File

@@ -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.

View File

@@ -228,11 +228,3 @@
- Из всех интерпретаторов скриптоты больше всех я люблю node.js, это самый быстрый в мире
интерпретатор, у него есть встроенная событийная машина, развитая инфраструктура и
приятный нейтральный C-подобный язык программирования. Поэтому Монитор реализован на node.js.
## Известные проблемы
- Удаление образов в деградированном кластере может в данный момент приводить к повторному
"появлению" удалённых объектов после поднятия отключённых OSD, причём в случае EC-пулов,
объекты могут появиться в виде "неполных". Если вы столкнётесь с такой ситуацией, просто
повторите запрос удаления. Данная проблема будет исправлена в будущем вместе с обновлением
дискового формата хранения метаданных.

View 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`.

View 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
View 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
View 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.

View File

@@ -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).

View File

@@ -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-сертификата).

View File

@@ -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',

View File

@@ -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 = [];

View File

@@ -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);

View File

@@ -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)

View File

@@ -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(

View File

@@ -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": {

View File

@@ -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,

View File

@@ -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}"

View File

@@ -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
View 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');

View 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');

View File

@@ -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;
}

View File

@@ -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": [

View File

@@ -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);
}

View File

@@ -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__)

View 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

View 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

View File

@@ -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++

View File

@@ -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++

View File

@@ -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++

View File

@@ -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++

View File

@@ -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)

View File

@@ -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; }
};

View File

@@ -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");
}

View File

@@ -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;
}

View File

@@ -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();
};

View File

@@ -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);
}

View File

@@ -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);

View File

@@ -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);
}

View File

@@ -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;

View File

@@ -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)
{

View File

@@ -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

View File

@@ -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;
}

View File

@@ -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:

View File

@@ -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;
}

View File

@@ -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())

View File

@@ -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>

View File

@@ -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;
}

View File

@@ -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);

View File

@@ -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;

View File

@@ -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);

View File

@@ -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,

View File

@@ -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++);
}
}

View File

@@ -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);

View File

@@ -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);
}
}

View File

@@ -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

View File

@@ -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();
}
}

View File

@@ -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)

View File

@@ -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);
}

View File

@@ -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)

View File

@@ -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);

View File

@@ -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;

View File

@@ -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();

View File

@@ -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;

View File

@@ -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);
}

View File

@@ -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())

View File

@@ -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);

View File

@@ -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);

View File

@@ -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
{

View File

@@ -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;

View File

@@ -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);
});
}

View File

@@ -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;

View File

@@ -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