diff --git a/docs/config/monitor.en.md b/docs/config/monitor.en.md index 6be7b18c..7e31299d 100644 --- a/docs/config/monitor.en.md +++ b/docs/config/monitor.en.md @@ -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 diff --git a/docs/config/monitor.ru.md b/docs/config/monitor.ru.md index e40b0316..d62322d4 100644 --- a/docs/config/monitor.ru.md +++ b/docs/config/monitor.ru.md @@ -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 - Тип: число diff --git a/docs/config/src/monitor.yml b/docs/config/src/monitor.yml index 0f586a4e..6458eed2 100644 --- a/docs/config/src/monitor.yml +++ b/docs/config/src/monitor.yml @@ -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 diff --git a/mon/etcd_schema.js b/mon/etcd_schema.js index 2874d8e4..ff994980 100644 --- a/mon/etcd_schema.js +++ b/mon/etcd_schema.js @@ -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', diff --git a/mon/mon.js b/mon/mon.js index f8cd907b..5e5edbc3 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 { @@ -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( diff --git a/mon/pg_gen.js b/mon/pg_gen.js index 21cdf68b..5f3b5501 100644 --- a/mon/pg_gen.js +++ b/mon/pg_gen.js @@ -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, diff --git a/mon/test-sticky-primaries.js b/mon/test-sticky-primaries.js new file mode 100644 index 00000000..f6cc4597 --- /dev/null +++ b/mon/test-sticky-primaries.js @@ -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');