From 06a5f987345427b763e6b931f58035a52a595ad5 Mon Sep 17 00:00:00 2001 From: Yury Luneff Date: Sat, 28 Nov 2026 00:45:58 +0300 Subject: [PATCH 1/4] mon: Add sticky_primaries to keep live primaries and balance new ones The monitor picks the primary OSD of a PG by PG number among the alive candidates and re-picks it on every OSD up/down. So when an OSD fails, live primaries of PGs that lost a member move too, and they all move back when it returns; every move restarts the PG on both OSDs. The rotation is also uneven: some OSDs become primary for several times more PGs than the average and peer them one after another. With sticky_primaries, a live primary stays while it is one of the PG's candidates, and a PG that needs a new primary gets the candidate which is primary for the fewest PGs of all pools, ties by PG number. The counts are shared by all pools of one change. Off by default. --- docs/config/monitor.en.md | 18 +++++ docs/config/monitor.ru.md | 19 ++++++ docs/config/src/monitor.yml | 28 ++++++++ mon/etcd_schema.js | 1 + mon/mon.js | 7 +- mon/pg_gen.js | 66 +++++++++++++++++-- mon/test-sticky-primaries.js | 123 +++++++++++++++++++++++++++++++++++ 7 files changed, 254 insertions(+), 8 deletions(-) create mode 100644 mon/test-sticky-primaries.js diff --git a/docs/config/monitor.en.md b/docs/config/monitor.en.md index 6be7b18c..7dd96255 100644 --- a/docs/config/monitor.en.md +++ b/docs/config/monitor.en.md @@ -24,6 +24,7 @@ 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) - [osd_backfillfull_ratio](#osd_backfillfull_ratio) ## use_antietcd @@ -180,6 +181,23 @@ 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. The other side of it is that a returned OSD only gets primaries +again when other PGs need a new primary. + ## osd_backfillfull_ratio - Type: number diff --git a/docs/config/monitor.ru.md b/docs/config/monitor.ru.md index e40b0316..dc85c5ae 100644 --- a/docs/config/monitor.ru.md +++ b/docs/config/monitor.ru.md @@ -24,6 +24,7 @@ - [osd_out_time](#osd_out_time) - [placement_levels](#placement_levels) - [use_old_pg_combinator](#use_old_pg_combinator) +- [sticky_primaries](#sticky_primaries) - [osd_backfillfull_ratio](#osd_backfillfull_ratio) ## use_antietcd @@ -183,6 +184,24 @@ 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 распределяются +равномернее и переносятся только тогда, когда это необходимо. Обратная сторона: +вернувшийся OSD снова получает первичные PG только тогда, когда новый +первичный OSD понадобится другим PG. + ## osd_backfillfull_ratio - Тип: число diff --git a/docs/config/src/monitor.yml b/docs/config/src/monitor.yml index 0f586a4e..2a5115ef 100644 --- a/docs/config/src/monitor.yml +++ b/docs/config/src/monitor.yml @@ -178,6 +178,34 @@ 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. The other side of it is that a returned OSD only gets primaries + again when other PGs need a new primary. + info_ru: | + Сохранять первичный OSD каждой PG, пока он жив и остаётся одним из + кандидатов в первичные OSD этой PG, а PG, которой нужен новый первичный OSD + (потому что прежний отказал или вышел из PG), отдавать тому кандидату, который + является первичным для наименьшего числа PG всех пулов. + + По умолчанию первичные OSD выбираются по номеру PG и возвращаются обратно, как + только их OSD снова включается. Каждый такой перенос перезапускает PG на обоих + OSD, а выбор по номеру PG может сделать часть OSD первичными для в несколько + раз большего числа PG, чем другие. С этой опцией первичные OSD распределяются + равномернее и переносятся только тогда, когда это необходимо. Обратная сторона: + вернувшийся OSD снова получает первичные PG только тогда, когда новый + первичный OSD понадобится другим PG. - name: osd_backfillfull_ratio type: float default: 0.99 diff --git a/mon/etcd_schema.js b/mon/etcd_schema.js index 2874d8e4..2e575290 100644 --- a/mon/etcd_schema.js +++ b/mon/etcd_schema.js @@ -64,6 +64,7 @@ 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, osd_backfillfull_ratio: 0.99, mon_metrics_path: '/prometheus', mon_healthcheck_path: '/healthcheck', diff --git a/mon/mon.js b/mon/mon.js index f8cd907b..04a6e395 100644 --- a/mon/mon.js +++ b/mon/mon.js @@ -16,7 +16,7 @@ const stableStringify = require('./stable-stringify.js'); const { scale_pg_history } = require('./pg_utils.js'); const { get_osd_tree } = require('./osd_tree.js'); const { b64, de64, local_ips } = require('./utils.js'); -const { recheck_primary, save_new_pgs_txn, generate_pool_pgs } = require('./pg_gen.js'); +const { recheck_primary, save_new_pgs_txn, generate_pool_pgs, count_primaries } = require('./pg_gen.js'); class Mon { @@ -613,6 +613,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 +628,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 +671,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( diff --git a/mon/pg_gen.js b/mon/pg_gen.js index 21cdf68b..8a927814 100644 --- a/mon/pg_gen.js +++ b/mon/pg_gen.js @@ -10,7 +10,8 @@ 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 +function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds, cur_primary = 0, counts = null) { let alive_set; if (pool_config.scheme === 'replicated') @@ -38,12 +39,53 @@ 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]; + } + // Moving a primary restarts the PG on both OSDs: keep a live one while it is a candidate + if (alive_set.includes(cur_primary)) + { + return cur_primary; + } + // Otherwise take 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; + } + } + return best; +} + +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) { let new_pg_config; + const counts = global_config.sticky_primaries ? count_primaries(state.pg.config) : null; for (const pool_id in state.config.pools) { const pool_cfg = state.config.pools[pool_id]; @@ -62,9 +104,11 @@ 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); if (pg_cfg.primary != new_primary) { + move_primary(counts, pg_cfg.primary, new_primary); if (!new_pg_config) { new_pg_config = JSON.parse(JSON.stringify(state.pg.config)); @@ -94,17 +138,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 +321,7 @@ function b64(str) } module.exports = { + count_primaries, recheck_primary, save_new_pgs_txn, generate_pool_pgs, diff --git a/mon/test-sticky-primaries.js b/mon/test-sticky-primaries.js new file mode 100644 index 00000000..8e1105d5 --- /dev/null +++ b/mon/test-sticky-primaries.js @@ -0,0 +1,123 @@ +// 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'); +} + +// 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_new_sets_keep_primaries(); +test_counts_on_pg_count_change(); +console.log('OK'); -- 2.47.3 From 5680fc61fe12bafce0dc34321826b9917c7eac3c Mon Sep 17 00:00:00 2001 From: Yury Luneff Date: Sat, 28 Nov 2026 01:13:40 +0300 Subject: [PATCH 2/4] mon: Even out sticky primaries once the cluster is calm With sticky_primaries a returned OSD got primaries again only when other PGs needed a new one. Once all PGs stay clean and no OSD goes up or down for primary_rebalance_time (300 s by default, 0 disables), move a live primary to the least loaded candidate of its PG when it has at least 2 primaries more. One pass gives each OSD at most one new primary, so no OSD re-peers a batch of PGs at once; the next pass waits until the cluster is calm again. --- docs/config/monitor.en.md | 17 ++++++++++-- docs/config/monitor.ru.md | 20 ++++++++++++--- docs/config/src/monitor.yml | 28 ++++++++++++++++---- mon/etcd_schema.js | 1 + mon/mon.js | 50 +++++++++++++++++++++++++++++++++++- mon/pg_gen.js | 23 ++++++++++------- mon/test-sticky-primaries.js | 27 +++++++++++++++++++ 7 files changed, 146 insertions(+), 20 deletions(-) diff --git a/docs/config/monitor.en.md b/docs/config/monitor.en.md index 7dd96255..7e31299d 100644 --- a/docs/config/monitor.en.md +++ b/docs/config/monitor.en.md @@ -25,6 +25,7 @@ These parameters only apply to Monitors. - [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 @@ -195,8 +196,20 @@ 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. The other side of it is that a returned OSD only gets primaries -again when other PGs need a new primary. +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 diff --git a/docs/config/monitor.ru.md b/docs/config/monitor.ru.md index dc85c5ae..d62322d4 100644 --- a/docs/config/monitor.ru.md +++ b/docs/config/monitor.ru.md @@ -25,6 +25,7 @@ - [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 @@ -198,9 +199,22 @@ OSD перед обновлением агрегированной статис только их OSD снова включается. Каждый такой перенос перезапускает PG на обоих OSD, а выбор по номеру PG может сделать часть OSD первичными для в несколько раз большего числа PG, чем другие. С этой опцией первичные OSD распределяются -равномернее и переносятся только тогда, когда это необходимо. Обратная сторона: -вернувшийся OSD снова получает первичные PG только тогда, когда новый -первичный OSD понадобится другим PG. +равномернее и переносятся только тогда, когда это необходимо, или когда в +кластере всё спокойно: см. [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 diff --git a/docs/config/src/monitor.yml b/docs/config/src/monitor.yml index 2a5115ef..6458eed2 100644 --- a/docs/config/src/monitor.yml +++ b/docs/config/src/monitor.yml @@ -191,8 +191,7 @@ 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. The other side of it is that a returned OSD only gets primaries - again when other PGs need a new primary. + have to, or when the cluster is calm: see [primary_rebalance_time](#primary_rebalance_time). info_ru: | Сохранять первичный OSD каждой PG, пока он жив и остаётся одним из кандидатов в первичные OSD этой PG, а PG, которой нужен новый первичный OSD @@ -203,9 +202,28 @@ только их OSD снова включается. Каждый такой перенос перезапускает PG на обоих OSD, а выбор по номеру PG может сделать часть OSD первичными для в несколько раз большего числа PG, чем другие. С этой опцией первичные OSD распределяются - равномернее и переносятся только тогда, когда это необходимо. Обратная сторона: - вернувшийся OSD снова получает первичные PG только тогда, когда новый - первичный OSD понадобится другим PG. + равномернее и переносятся только тогда, когда это необходимо, или когда в + кластере всё спокойно: см. [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 diff --git a/mon/etcd_schema.js b/mon/etcd_schema.js index 2e575290..ff994980 100644 --- a/mon/etcd_schema.js +++ b/mon/etcd_schema.js @@ -65,6 +65,7 @@ const etcd_tree = { 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', diff --git a/mon/mon.js b/mon/mon.js index 04a6e395..1c03b6cc 100644 --- a/mon/mon.js +++ b/mon/mon.js @@ -74,6 +74,7 @@ class Mon this.state = JSON.parse(JSON.stringify(etcd_tree)); this.prev_stats = { osd_stats: {}, osd_diff: {} }; this.recheck_pgs_active = false; + this.last_unclean_time = Date.now(); this.updating_total_stats = false; this.watcher_active = false; this.old_pg_config = false; @@ -199,6 +200,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 +221,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 +280,33 @@ 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.config.sticky_primaries || + !this.config.primary_rebalance_time) + { + return; + } + const wait = (this.last_unclean_time||0) + this.config.primary_rebalance_time*1000 - Date.now(); + this.primary_rebalance_timer = setTimeout(() => + { + this.primary_rebalance_timer = null; + if (!this.all_pgs_clean) + { + return; + } + if (Date.now() < this.last_unclean_time + this.config.primary_rebalance_time*1000) + { + this.schedule_primary_rebalance(); + return; + } + this.primary_rebalance_due = true; + this.schedule_recheck(); + }, wait > 0 ? wait : 0); + } + async save_last_clean() { if (this.save_last_clean_running) @@ -285,6 +317,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 +335,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 +413,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 +558,8 @@ class Mon return; } this.recheck_pgs_active = true; + const rebalance_primaries = this.primary_rebalance_due; + this.primary_rebalance_due = false; // 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 @@ -564,7 +611,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 +620,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(); } } diff --git a/mon/pg_gen.js b/mon/pg_gen.js index 8a927814..5f3b5501 100644 --- a/mon/pg_gen.js +++ b/mon/pg_gen.js @@ -11,7 +11,8 @@ 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'); // cur_primary and counts ({ osd_num: primaries } over all pools) are only passed with sticky_primaries -function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds, cur_primary = 0, counts = null) +// 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') @@ -43,12 +44,7 @@ function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds, { return alive_set[pg_num % alive_set.length]; } - // Moving a primary restarts the PG on both OSDs: keep a live one while it is a candidate - if (alive_set.includes(cur_primary)) - { - return cur_primary; - } - // Otherwise take the candidate with the fewest primaries, ties by PG number + // The candidate with the fewest primaries, ties by PG number let best = 0; for (let i = 0; i < alive_set.length; i++) { @@ -58,6 +54,12 @@ function pick_primary(pool_id, pg_num, pool_config, osd_set, up_osds, aff_osds, 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; } @@ -82,10 +84,11 @@ function move_primary(counts, from, to) counts[to] = (counts[to]||0) + 1; } -function recheck_primary(state, global_config, up_osds, osd_tree) +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]; @@ -105,10 +108,12 @@ function recheck_primary(state, global_config, up_osds, osd_tree) 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, pg_cfg.primary, counts); + 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)); diff --git a/mon/test-sticky-primaries.js b/mon/test-sticky-primaries.js index 8e1105d5..f6cc4597 100644 --- a/mon/test-sticky-primaries.js +++ b/mon/test-sticky-primaries.js @@ -82,6 +82,32 @@ function test_host_restart() 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() { @@ -118,6 +144,7 @@ function test_counts_on_pg_count_change() 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'); -- 2.47.3 From 39b20040accdc2ef5fe31ce63edf1e37bbdc5e07 Mon Sep 17 00:00:00 2001 From: Yury Luneff Date: Sat, 28 Nov 2026 01:32:02 +0300 Subject: [PATCH 3/4] mon: Check calm again when the primary rebalance runs A monitor that took over a clean cluster never armed the rebalance timer, an OSD could go down between the timer and the pass, and setting primary_rebalance_time to 0 did not cancel an armed pass. Check calm in one place, when the timer fires and again when the pass runs, and run save_last_clean() on start. --- mon/mon.js | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/mon/mon.js b/mon/mon.js index 1c03b6cc..c69066e0 100644 --- a/mon/mon.js +++ b/mon/mon.js @@ -145,6 +145,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(); } @@ -284,29 +286,34 @@ class Mon // for primary_rebalance_time schedule_primary_rebalance() { - if (this.stopped || this.primary_rebalance_timer || !this.config.sticky_primaries || + if (this.stopped || this.primary_rebalance_timer || !this.all_pgs_clean || !this.config.sticky_primaries || !this.config.primary_rebalance_time) { return; } - const wait = (this.last_unclean_time||0) + this.config.primary_rebalance_time*1000 - Date.now(); + 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.all_pgs_clean) + if (this.primary_rebalance_calm()) { - return; + this.primary_rebalance_due = true; + this.schedule_recheck(); } - if (Date.now() < this.last_unclean_time + this.config.primary_rebalance_time*1000) + else { this.schedule_primary_rebalance(); - return; } - this.primary_rebalance_due = true; - this.schedule_recheck(); }, 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) @@ -558,7 +565,9 @@ class Mon return; } this.recheck_pgs_active = true; - const rebalance_primaries = this.primary_rebalance_due; + 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; // Take configuration and state, check it against the stored configuration hash // Recalculate PGs and save them to etcd if the configuration is changed -- 2.47.3 From 7b4c0825b4ab2964f7068fe72a578c30abcae786 Mon Sep 17 00:00:00 2001 From: Yury Luneff Date: Sat, 28 Nov 2026 03:13:17 +0300 Subject: [PATCH 4/4] mon: Restart the primary rebalance wait on takeover and after a pass A standby monitor sees no changes, so on takeover it could run a pass at once, and a pass could follow another before the moved PGs reported their state. Restart the wait when the monitor becomes master and when a pass runs. Re-arm the timer when the pass lands on a re-optimize round instead of dropping it, and treat a negative value as 0. --- mon/mon.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/mon/mon.js b/mon/mon.js index c69066e0..5e5edbc3 100644 --- a/mon/mon.js +++ b/mon/mon.js @@ -74,7 +74,6 @@ class Mon this.state = JSON.parse(JSON.stringify(etcd_tree)); this.prev_stats = { osd_stats: {}, osd_diff: {} }; this.recheck_pgs_active = false; - this.last_unclean_time = Date.now(); this.updating_total_stats = false; this.watcher_active = false; this.old_pg_config = false; @@ -131,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; @@ -287,7 +288,7 @@ class Mon schedule_primary_rebalance() { if (this.stopped || this.primary_rebalance_timer || !this.all_pgs_clean || !this.config.sticky_primaries || - !this.config.primary_rebalance_time) + !(this.config.primary_rebalance_time > 0)) { return; } @@ -569,6 +570,9 @@ class Mon 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 @@ -581,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 -- 2.47.3