osd: Wait for the old state lease to expire instead of exiting #140

Open
koolkhel wants to merge 1 commits from koolkhel/vitastor:osd-wait-old-lease into master
Contributor

Description

An OSD killed with SIGKILL or by a power loss can't revoke its etcd lease, so its
/osd/state key stays until the lease expires. An OSD restarted before that prints
Key ... already exists in etcd, OSD N is still up and exits. systemd starts it again 10
seconds later, and each start loads the whole blockstore before it gets to this check.

After a power loss of the whole cluster this happens to most OSDs: etcd doesn't store lease
expiry times, and a newly elected leader gives every lease its full TTL again
(lessor.Promote()), so the keys of the previous boot live for one more TTL, and again
after every further leader change.

The change:

  • After the blockstore is loaded and before bind_socket() and acquire_lease(), the OSD
    reads its state key. While the key exists and has a lease, it checks it again every
    etcd_quick_timeout (1 second by default). It logs one line when the wait starts:
    [OSD 1] Key /vitastor/osd/state/1 already exists in etcd, waiting up to 45 seconds for its lease to expire.
  • The total wait is limited to 3 lease TTLs. After that the OSD goes on as before:
    create_osd_state() finds the key and exits with code 1 and the old message, because
    another OSD with the same number really is up. A key without a lease is not waited for.
  • While it waits, the OSD doesn't listen and holds no lease, so it accepts no requests and
    writes nothing to etcd. acquire_lease() and create_osd_state() work as before.

Tested:

  • New tests/test_osd_restart.sh: kill -9 an OSD and start it again at once, without
    deleting the state key by hand. It has to wait without listening sockets, then register
    and listen. Then a second OSD with the same number has to exit with an error and leave
    the state key of the first one alone. The test fails on master (the restarted OSD exits)
    and passes with the change, with etcd 3.5.15 and with ANTIETCD=1 (about a minute each).
  • osd_test, test_switch_primary.sh, test_rm_degraded.sh pass.

Contributor Name

Yury Luneff (MIND Software LLC, https://mindsw.io)

CLA

### Description An OSD killed with SIGKILL or by a power loss can't revoke its etcd lease, so its `/osd/state` key stays until the lease expires. An OSD restarted before that prints `Key ... already exists in etcd, OSD N is still up` and exits. systemd starts it again 10 seconds later, and each start loads the whole blockstore before it gets to this check. After a power loss of the whole cluster this happens to most OSDs: etcd doesn't store lease expiry times, and a newly elected leader gives every lease its full TTL again (`lessor.Promote()`), so the keys of the previous boot live for one more TTL, and again after every further leader change. The change: - After the blockstore is loaded and before `bind_socket()` and `acquire_lease()`, the OSD reads its state key. While the key exists and has a lease, it checks it again every `etcd_quick_timeout` (1 second by default). It logs one line when the wait starts: `[OSD 1] Key /vitastor/osd/state/1 already exists in etcd, waiting up to 45 seconds for its lease to expire`. - The total wait is limited to 3 lease TTLs. After that the OSD goes on as before: `create_osd_state()` finds the key and exits with code 1 and the old message, because another OSD with the same number really is up. A key without a lease is not waited for. - While it waits, the OSD doesn't listen and holds no lease, so it accepts no requests and writes nothing to etcd. `acquire_lease()` and `create_osd_state()` work as before. Tested: - New `tests/test_osd_restart.sh`: `kill -9` an OSD and start it again at once, without deleting the state key by hand. It has to wait without listening sockets, then register and listen. Then a second OSD with the same number has to exit with an error and leave the state key of the first one alone. The test fails on master (the restarted OSD exits) and passes with the change, with etcd 3.5.15 and with `ANTIETCD=1` (about a minute each). - `osd_test`, `test_switch_primary.sh`, `test_rm_degraded.sh` pass. ### Contributor Name Yury Luneff (MIND Software LLC, https://mindsw.io) ### CLA - [x] I accept Vitastor CLA agreement: https://git.yourcmc.ru/vitalif/vitastor/src/branch/master/CLA-en.md
koolkhel added 1 commit 2026-11-20 16:29:07 +03:00
An OSD killed with SIGKILL or by a power loss can't revoke its etcd
lease, so its /osd/state key stays until the lease expires. An OSD
restarted before that printed "OSD N is still up" and exited, to be
started again by systemd after one more full blockstore load. etcd also
gives every lease a full TTL again when its leader changes, so after a
power loss of the whole cluster most OSDs go through this, some of them
several times.

Ask etcd how long the old lease has left (/lease/timetolive), wait that
long and retry. If the call fails (antietcd doesn't have it), wait a
full lease TTL. Give up as before after 3 TTLs in total: then another
OSD with this number really is up. Treat a key that already has our own
lease as registered: it means that the reply to the previous attempt
was lost.

Start reporting statistics only after the registration, so that a
second OSD with the same number can't overwrite /osd/stats while it
waits.
Owner

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

В принципе идея неплохая, но нужно тогда ещё все bind_socket запускать после получения lease, чтобы случайно запросы не начать принимать.
vitalif requested changes 2026-11-20 19:18:36 +03:00
vitalif left a comment
Owner

выше отписал

выше отписал
Author
Contributor

Переделал: ожидание теперь идёт до bind_socket().

  • Новая wait_old_osd_state() вызывается после init_blockstore вместо пары bind_socket() + acquire_lease(). Она читает ключ /osd/state/N. Если ключ есть и у него есть lease, спрашивает /lease/timetolive, ждёт и проверяет снова, всего не больше 3 TTL. Когда ключа нет, вызывает bind_socket() и acquire_lease(), как раньше.
  • Перенести bind совсем после создания ключа нельзя: в ключе лежит порт, а при bind_port=0 его назначает ядро. Поэтому порядок такой: дождаться, пока старый ключ исчезнет → bind → lease → ключ. Окно между bind и ключом осталось таким же, как в master.
  • Пока OSD ждёт, он не слушает и не держит lease. Поэтому acquire_lease() и create_osd_state() остались как в master, а правки про «свой lease в ключе» и про таймер статистики стали не нужны, я их убрал. Если после 3 TTL ключ всё ещё есть, create_osd_state() пишет «OSD N is still up» и выходит, как раньше.
  • Тест tests/test_osd_restart.sh теперь проверяет через ss, что у ждущего OSD нет слушающих сокетов, а после регистрации они есть. На прошлой версии ветки эта проверка падает.

Ветку перебазировал на текущий master (force-push). Описание PR выше осталось от первой версии.

Переделал: ожидание теперь идёт до `bind_socket()`. - Новая `wait_old_osd_state()` вызывается после `init_blockstore` вместо пары `bind_socket()` + `acquire_lease()`. Она читает ключ `/osd/state/N`. Если ключ есть и у него есть lease, спрашивает `/lease/timetolive`, ждёт и проверяет снова, всего не больше 3 TTL. Когда ключа нет, вызывает `bind_socket()` и `acquire_lease()`, как раньше. - Перенести bind совсем после создания ключа нельзя: в ключе лежит порт, а при `bind_port=0` его назначает ядро. Поэтому порядок такой: дождаться, пока старый ключ исчезнет → bind → lease → ключ. Окно между bind и ключом осталось таким же, как в master. - Пока OSD ждёт, он не слушает и не держит lease. Поэтому `acquire_lease()` и `create_osd_state()` остались как в master, а правки про «свой lease в ключе» и про таймер статистики стали не нужны, я их убрал. Если после 3 TTL ключ всё ещё есть, `create_osd_state()` пишет «OSD N is still up» и выходит, как раньше. - Тест `tests/test_osd_restart.sh` теперь проверяет через `ss`, что у ждущего OSD нет слушающих сокетов, а после регистрации они есть. На прошлой версии ветки эта проверка падает. Ветку перебазировал на текущий master (force-push). Описание PR выше осталось от первой версии.
koolkhel force-pushed osd-wait-old-lease from dace9b6392 to 15db867957 2026-11-21 10:20:13 +03:00 Compare
vitalif requested changes 2026-11-22 15:26:58 +03:00
@@ -530,0 +565,4 @@
{ "ID", old_lease }
}, st_cli->etcd_quick_timeout, 0, 0, [this, state_key, waited, max_wait](std::string err, json11::Json data)
{
// Wait a full TTL if etcd can't tell how much of it is left (antietcd)
Owner

Может быть не пытаться спать полный интервал при неудаче, а просто ретраить получение лизы до успеха с равными интервалами типа 1 секунды или более?

Может быть не пытаться спать полный интервал при неудаче, а просто ретраить получение лизы до успеха с равными интервалами типа 1 секунды или более?
koolkhel reviewed 2026-11-22 16:55:42 +03:00
@@ -530,0 +565,4 @@
{ "ID", old_lease }
}, st_cli->etcd_quick_timeout, 0, 0, [this, state_key, waited, max_wait](std::string err, json11::Json data)
{
// Wait a full TTL if etcd can't tell how much of it is left (antietcd)
Author
Contributor

Сделал так: убрал /lease/timetolive и расчёт интервала совсем. Теперь OSD просто перепроверяет ключ раз в etcd_quick_timeout (1 с по умолчанию), пока он не исчезнет, одинаково для etcd и antietcd. Ограничение в 3 TTL оставил: после него create_osd_state() находит ключ и выходит с «OSD N is still up», как в master.

Сделал так: убрал `/lease/timetolive` и расчёт интервала совсем. Теперь OSD просто перепроверяет ключ раз в `etcd_quick_timeout` (1 с по умолчанию), пока он не исчезнет, одинаково для etcd и antietcd. Ограничение в 3 TTL оставил: после него `create_osd_state()` находит ключ и выходит с «OSD N is still up», как в master.
koolkhel force-pushed osd-wait-old-lease from 15db867957 to 2edaa05bd0 2026-11-22 16:55:56 +03:00 Compare
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u osd-wait-old-lease:koolkhel-osd-wait-old-lease
git checkout koolkhel-osd-wait-old-lease
Sign in to join this conversation.
No Reviewers
No Label
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: vitalif/vitastor#140
No description provided.